From aa9b9ea5d624c8b48db442aeaa42830bc85bb40a Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sat, 14 Nov 2026 23:47:57 -0800 Subject: [PATCH 01/10] chore: add REUSE licensing metadata Add REUSE.toml and the license texts under LICENSES/ so the repository is REUSE 3.3 compliant before code arrives. Documentation, repository metadata, test configuration and fixtures, and translation catalogs are annotated in REUSE.toml; every source file carries its own SPDX header. The code of conduct keeps its Contributor Covenant attribution under CC-BY-4.0. Refs #32 Signed-off-by: Thomas Vincent --- LICENSES/CC-BY-4.0.txt | 156 ++++++++++++++++++++++++++++++++++ LICENSES/GPL-2.0-or-later.txt | 117 +++++++++++++++++++++++++ REUSE.toml | 32 +++++++ 3 files changed, 305 insertions(+) create mode 100644 LICENSES/CC-BY-4.0.txt create mode 100644 LICENSES/GPL-2.0-or-later.txt create mode 100644 REUSE.toml diff --git a/LICENSES/CC-BY-4.0.txt b/LICENSES/CC-BY-4.0.txt new file mode 100644 index 0000000..13ca539 --- /dev/null +++ b/LICENSES/CC-BY-4.0.txt @@ -0,0 +1,156 @@ +Creative Commons Attribution 4.0 International + + Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. + +Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + + a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + + d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + + g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. + + i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + + 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. Downstream recipients. + + A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + +b. Other rights. + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; + + b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + + a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. + + b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. + + c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + + a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + + d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +Section 8 – Interpretation. + + a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + + c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + + d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSES/GPL-2.0-or-later.txt b/LICENSES/GPL-2.0-or-later.txt new file mode 100644 index 0000000..17cb286 --- /dev/null +++ b/LICENSES/GPL-2.0-or-later.txt @@ -0,0 +1,117 @@ +GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. + + c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author + + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. + +signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 0000000..6eb8db1 --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,32 @@ +version = 1 + +# Files that cannot carry a comment header, or whose format makes one +# awkward: documentation, repository metadata, GitHub templates, test +# configuration and fixtures, and translation catalogs, which gettext +# regenerates. +[[annotations]] +path = [ + "README.md", + "CONTRIBUTING.md", + "SECURITY.md", + "docs/**", + ".github/**", + ".editorconfig", + ".gitattributes", + "REUSE.toml", + "phpunit.xml", + "phpunit-integration.xml", + "tests/fixtures/**", + "locales/po/**", + "locales/LC_MESSAGES/**", +] +precedence = "aggregate" +SPDX-FileCopyrightText = "2026 Thomas Vincent " +SPDX-License-Identifier = "GPL-2.0-or-later" + +# Contributor Covenant 2.0, adapted. +[[annotations]] +path = "CODE_OF_CONDUCT.md" +precedence = "aggregate" +SPDX-FileCopyrightText = "Contributor Covenant contributors " +SPDX-License-Identifier = "CC-BY-4.0" From 6a13f4028ae92c028d3ba0948e2e9df77c7a5c42 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 00:15:49 -0800 Subject: [PATCH 02/10] feat: plugin skeleton with PHP 8.2 guard and lifecycle Add setup.php, INFO, the lib/ class loader, versioned schema migrations, settings, realms, logging, and the translation template, following the layout of plugin_cloud's foundation. setup.php and everything Cacti includes before the version check parse on PHP 8.0. Install and check_config refuse below PHP 8.2 with a message naming the required version; hook shims return before the autoloader is registered, so no class file is parsed on an unsupported runtime. Install and upgrade share one path: tables are created through Cacti's tracked plugin table API, hooks and realms are registered from a *_setup_* function, and the recorded plugin version changes only after every migration succeeds. Uninstall keeps the plugin tables unless the administrator cleared Keep Plugin Tables on Uninstall, on supported and refused runtimes alike, and never touches Cacti devices, graphs, or RRD files. Logging goes through cacti_log() under the GPU tag, and strings use the gpu text domain. Unit and source-rule suites cover the guard, settings defaults and ranges, realms, the one-class-per-file layout, prepared SQL only in repositories, raw request variables, the text domain, and a ban on starting any process or naming a state-changing vendor command. Provisional decisions taken here (issues #11 and #12 stay open): - Plugin directory and name "gpu"; namespace Somethingwithproof\Gpu rather than the Cacti\Gpu that REQ-CODE-001 names, until #11 settles the repository home. - Test harness: Pest from Cacti's locked plugin harness, as maintained plugins and plugin_cloud use it. Refs #29, #30, #32 Signed-off-by: Thomas Vincent --- INFO | 25 +++ include/autoload.php | 45 +++++ include/unbooted-uninstall.php | 39 ++++ index.php | 20 ++ lib/AdminState.php | 25 +++ lib/Clock.php | 24 +++ lib/FixedClock.php | 36 ++++ lib/Log.php | 44 +++++ lib/Pages.php | 90 +++++++++ lib/Row.php | 114 +++++++++++ lib/Schema.php | 236 ++++++++++++++++++++++ lib/Settings.php | 88 +++++++++ lib/SettingsRepository.php | 45 +++++ lib/SystemClock.php | 26 +++ locales/build_gettext.sh | 111 +++++++++++ locales/index.php | 20 ++ locales/po/cacti.pot | 79 ++++++++ phpstan.neon | 38 ++++ phpunit.xml | 28 +++ setup.php | 269 +++++++++++++++++++++++++ tests/Pest.php | 22 +++ tests/Security/SourceRulesTest.php | 302 +++++++++++++++++++++++++++++ tests/Unit/BootTest.php | 64 ++++++ tests/Unit/LifecycleUnitTest.php | 108 +++++++++++ tests/Unit/RowTest.php | 108 +++++++++++ tests/bootstrap-unit.php | 172 ++++++++++++++++ tests/phpstan-bootstrap.php | 28 +++ 27 files changed, 2206 insertions(+) create mode 100644 INFO create mode 100644 include/autoload.php create mode 100644 include/unbooted-uninstall.php create mode 100644 index.php create mode 100644 lib/AdminState.php create mode 100644 lib/Clock.php create mode 100644 lib/FixedClock.php create mode 100644 lib/Log.php create mode 100644 lib/Pages.php create mode 100644 lib/Row.php create mode 100644 lib/Schema.php create mode 100644 lib/Settings.php create mode 100644 lib/SettingsRepository.php create mode 100644 lib/SystemClock.php create mode 100755 locales/build_gettext.sh create mode 100644 locales/index.php create mode 100644 locales/po/cacti.pot create mode 100644 phpstan.neon create mode 100644 phpunit.xml create mode 100644 setup.php create mode 100644 tests/Pest.php create mode 100644 tests/Security/SourceRulesTest.php create mode 100644 tests/Unit/BootTest.php create mode 100644 tests/Unit/LifecycleUnitTest.php create mode 100644 tests/Unit/RowTest.php create mode 100644 tests/bootstrap-unit.php create mode 100644 tests/phpstan-bootstrap.php diff --git a/INFO b/INFO new file mode 100644 index 0000000..69c14bb --- /dev/null +++ b/INFO @@ -0,0 +1,25 @@ +; SPDX-FileCopyrightText: 2026 Thomas Vincent +; SPDX-License-Identifier: GPL-2.0-or-later +; +; This file is part of plugin_gpu, a plugin for Cacti. +; https://github.com/somethingwithproof/plugin_gpu +; +; This program is free software; you can redistribute it and/or modify it +; under the terms of the GNU General Public License as published by the Free +; Software Foundation; either version 2 of the License, or (at your option) +; any later version. +; +; This program is distributed in the hope that it will be useful, but WITHOUT +; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +; more details. + +[info] +name = gpu +version = 0.1.0-dev +longname = GPU +author = "Thomas Vincent (somethingwithproof)" +email = thomasvincent@gmail.com +homepage = https://github.com/somethingwithproof/plugin_gpu +compat = 1.2.31 +capabilities = online_view:1, online_mgmt:1, offline_view:0, offline_mgmt:0 diff --git a/include/autoload.php b/include/autoload.php new file mode 100644 index 0000000..164fedc --- /dev/null +++ b/include/autoload.php @@ -0,0 +1,45 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Class loader for lib/. Required only by gpu_boot() after the PHP version + * check, so class files may use PHP 8.2 syntax. This file itself stays PHP 8.0 + * compatible because it sits on the include path of setup.php. + */ + +spl_autoload_register(function ($class) { + $prefix = 'Somethingwithproof\\Gpu\\'; + + if (strncmp($class, $prefix, strlen($prefix)) !== 0) { + return; + } + + $name = substr($class, strlen($prefix)); + + // One flat directory: a namespace separator in the remainder is never ours. + if (strpos($name, '\\') !== false) { + return; + } + + $file = dirname(__DIR__) . '/lib/' . $name . '.php'; + + if (is_file($file)) { + require_once($file); + } +}); diff --git a/include/unbooted-uninstall.php b/include/unbooted-uninstall.php new file mode 100644 index 0000000..a19424f --- /dev/null +++ b/include/unbooted-uninstall.php @@ -0,0 +1,39 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Uninstall on a runtime the plugin refuses (PHP below 8.2), where nothing + * under lib/ may load. Cacti goes on to drop every tracked plugin table after + * plugin_gpu_uninstall() returns, so the keep tables setting must be honoured + * here too, in PHP 8.0 syntax. It mirrors Settings::fromRow() and + * Schema::untrackTables() / forgetVersion(); the lifecycle integration tests + * run both paths. + */ + +function gpu_uninstall_unbooted(): void { + $row = db_fetch_row_prepared('SELECT value FROM settings WHERE name = ?', array('gpu_uninstall_keep_tables')); + $keep = !is_array($row) || $row === array() || (isset($row['value']) && $row['value'] === 'on'); + + if ($keep) { + db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", array('gpu')); + cacti_log('NOTE: Uninstall kept the plugin tables as configured', false, 'GPU'); + } else { + db_execute_prepared('DELETE FROM settings WHERE name = ?', array('gpu_schema_version')); + } +} diff --git a/index.php b/index.php new file mode 100644 index 0000000..102f0ad --- /dev/null +++ b/index.php @@ -0,0 +1,20 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +header('Location: ../index.php'); diff --git a/lib/AdminState.php b/lib/AdminState.php new file mode 100644 index 0000000..db16391 --- /dev/null +++ b/lib/AdminState.php @@ -0,0 +1,25 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +enum AdminState: string { + case Enabled = 'enabled'; + case Disabled = 'disabled'; +} diff --git a/lib/Clock.php b/lib/Clock.php new file mode 100644 index 0000000..b954626 --- /dev/null +++ b/lib/Clock.php @@ -0,0 +1,24 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +interface Clock { + public function now(): int; +} diff --git a/lib/FixedClock.php b/lib/FixedClock.php new file mode 100644 index 0000000..0964111 --- /dev/null +++ b/lib/FixedClock.php @@ -0,0 +1,36 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * A clock that stays where it is put, for tests and for replaying a run. + */ +final class FixedClock implements Clock { + public function __construct(private int $time) { + } + + public function now(): int { + return $this->time; + } + + public function advance(int $seconds): void { + $this->time += $seconds; + } +} diff --git a/lib/Log.php b/lib/Log.php new file mode 100644 index 0000000..2218fa5 --- /dev/null +++ b/lib/Log.php @@ -0,0 +1,44 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Plugin log lines go through cacti_log() under the GPU tag, so they share + * Cacti's log file, rotation, and verbosity filter (REQ-CODE-006). Callers + * name nodes and GPUs by their plugin record ids at the default level, never + * by hostname, serial number, or raw tool output. + */ +final class Log { + public static function debug(string $message): void { + cacti_log('DEBUG: ' . $message, false, 'GPU', POLLER_VERBOSITY_DEBUG); + } + + public static function info(string $message): void { + cacti_log('NOTE: ' . $message, false, 'GPU', POLLER_VERBOSITY_MEDIUM); + } + + public static function warning(string $message): void { + cacti_log('WARNING: ' . $message, false, 'GPU'); + } + + public static function error(string $message): void { + cacti_log('ERROR: ' . $message, false, 'GPU'); + } +} diff --git a/lib/Pages.php b/lib/Pages.php new file mode 100644 index 0000000..8a8cc44 --- /dev/null +++ b/lib/Pages.php @@ -0,0 +1,90 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Page files, realms, menu entries, and breadcrumbs. + * + * Cacti's auth.php denies any page that is not listed in a realm, so every + * page script the plugin ships must appear in exactly one realm below + * (REQ-UI-001, REQ-UI-005). Pages that change node or GPU records are GPU + * Admin pages; GPU View pages only read. + */ +final class Pages { + public const VIEW = ['gpu_inventory.php']; + public const ADMIN = ['gpu_nodes.php']; + + /** + * @return list}> + */ + public static function realms(): array { + return [ + ['name' => __('GPU View', 'gpu'), 'files' => self::VIEW], + ['name' => __('GPU Admin', 'gpu'), 'files' => self::ADMIN], + ]; + } + + /** + * @return list + */ + public static function files(): array { + return array_merge(self::VIEW, self::ADMIN); + } + + /** + * Console > Management entries. + * + * @return array + */ + public static function menu(): array { + return [ + 'gpu_nodes.php' => __('GPU Nodes', 'gpu'), + 'gpu_inventory.php' => __('GPU Inventory', 'gpu'), + ]; + } + + /** + * Pages whose load re-checks the schema, matching how maintained plugins + * apply upgrades in a core that never calls plugin_*_upgrade() itself. + * + * @return list + */ + public static function upgradeTriggers(): array { + return array_merge(['plugins.php'], self::files()); + } + + /** + * @return array + */ + public static function navigation(): array { + $nav = []; + + foreach (self::menu() as $file => $title) { + $nav[$file . ':'] = [ + 'title' => $title, + 'mapping' => 'index.php:', + 'url' => $file, + 'level' => '1', + ]; + } + + return $nav; + } +} diff --git a/lib/Row.php b/lib/Row.php new file mode 100644 index 0000000..117111a --- /dev/null +++ b/lib/Row.php @@ -0,0 +1,114 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Normalization rules for loose values read from Cacti's database. + * + * Only fromRow() constructors call these. Cacti stores most values as strings + * and NULL, '' and malformed text all appear in real rows, so each rule names + * what it does with them. tests/Unit/RowTest.php pins these choices; changing + * one changes comparisons everywhere a value object is built. + */ +final class Row { + /** + * Integer column. Missing, NULL, '', and anything that is not a whole + * decimal number (including '1.5', '1e3', and '12abc') yield $default, as + * does a value below $min. + * + * @param array $row + */ + public static function int(array $row, string $key, int $default = 0, int $min = PHP_INT_MIN): int { + $value = $row[$key] ?? null; + + if (is_int($value)) { + $int = $value; + } elseif (is_string($value) && preg_match('/^\s*-?\d{1,18}\s*$/', $value) === 1) { + $int = (int) $value; + } else { + return $default; + } + + return $int < $min ? $default : $int; + } + + /** + * Measured value. NULL, '', rrdtool's 'U', 'nan', and other non-numeric + * text yield null (unknown). Zero stays zero: unknown and zero are + * different measurements. + * + * @param array $row + */ + public static function float(array $row, string $key): ?float { + $value = $row[$key] ?? null; + + if (is_int($value) || is_float($value)) { + $float = (float) $value; + } elseif (is_string($value) && is_numeric(trim($value))) { + $float = (float) trim($value); + } else { + return null; + } + + return is_finite($float) ? $float : null; + } + + /** + * Text column. Missing and NULL yield ''; scalars are cast and trimmed; + * arrays and objects yield ''. + * + * @param array $row + */ + public static function string(array $row, string $key): string { + $value = $row[$key] ?? null; + + return is_scalar($value) ? trim((string) $value) : ''; + } + + /** + * Result of a db_fetch_assoc*() call, which returns false on error. An + * error reads as no rows, and non-array rows are dropped. + * + * @return list> + */ + public static function rows(mixed $rows): array { + return is_array($rows) ? array_values(array_filter($rows, 'is_array')) : []; + } + + /** + * Flag column, including Cacti checkbox settings ('on' or ''). Only 'on', + * 'yes', 'true', '1', 1 and true are true; everything else is false. + * + * @param array $row + */ + public static function bool(array $row, string $key): bool { + $value = $row[$key] ?? null; + + if (is_bool($value)) { + return $value; + } + + if (is_int($value)) { + return $value === 1; + } + + return is_string($value) && in_array(strtolower(trim($value)), ['on', 'yes', 'true', '1'], true); + } +} diff --git a/lib/Schema.php b/lib/Schema.php new file mode 100644 index 0000000..5b26022 --- /dev/null +++ b/lib/Schema.php @@ -0,0 +1,236 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Plugin tables, their migrations, and the plugin's registration records. + * + * Tables are created through api_plugin_db_table_create() so Cacti tracks them + * in plugin_db_changes and drops them on uninstall. The schema version is kept + * in its own setting because api_plugin_install() writes plugin_config.version + * before the plugin's install function runs, so that column cannot tell us + * whether the tables exist. + * + * Migrations run once each, in order, and the stored schema version moves + * past a migration only after it succeeds (REQ-LIFE-002). Every migration is + * written to be safe to repeat, so one interrupted part way is completed by + * the next run. No migration touches a Cacti device, data source, graph, or + * RRD file, or contacts a GPU node (REQ-LIFE-003, REQ-LIFE-005). + */ +final class Schema { + public const VERSION = 1; + + public const HOOKS = [ + 'config_arrays' => 'gpu_config_arrays', + 'config_settings' => 'gpu_config_settings', + 'draw_navigation_text' => 'gpu_draw_navigation_text', + ]; + + private const PLUGIN = 'gpu'; + private const SETTING = 'gpu_schema_version'; + + public function __construct(private readonly \PDO|false $connection) { + } + + public function storedVersion(): int { + $value = db_fetch_cell_prepared('SELECT value FROM settings WHERE name = ?', [self::SETTING], '', true, $this->connection); + + return is_numeric($value) ? (int) $value : 0; + } + + public function isCurrent(): bool { + return $this->storedVersion() === self::VERSION; + } + + /** + * Apply every pending migration, or stop at the first that fails. + * + * @param int $through the last migration to run; tests pass a lower + * number to leave an upgrade interrupted + */ + public function migrate(int $through = self::VERSION): bool { + $from = $this->storedVersion(); + + if ($from > self::VERSION) { + Log::error(sprintf('Schema version %d is newer than this code (%d); refusing to downgrade', $from, self::VERSION)); + + return false; + } + + foreach ($this->migrations() as $version => $migration) { + if ($version <= $from || $version > $through) { + continue; + } + + if (!$migration()) { + Log::error(sprintf('Schema migration %d failed; schema left at version %d', $version, $this->storedVersion())); + + return false; + } + + db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', [self::SETTING, (string) $version], true, $this->connection); + + Log::info(sprintf('Schema migrated to version %d', $version)); + } + + return true; + } + + public function recordedPluginVersion(): string { + return (string) db_fetch_cell_prepared('SELECT version FROM plugin_config WHERE directory = ?', [self::PLUGIN], '', true, $this->connection); + } + + public function recordPluginVersion(string $version, string $author, string $homepage): void { + db_execute_prepared('UPDATE plugin_config SET version = ?, author = ?, webpage = ? WHERE directory = ?', [$version, $author, $homepage, self::PLUGIN], true, $this->connection); + } + + public function hooksRegistered(): bool { + $placeholders = implode(', ', array_fill(0, count(self::HOOKS), '?')); + + $hooks = (int) db_fetch_cell_prepared("SELECT COUNT(DISTINCT hook) FROM plugin_hooks WHERE name = ? AND hook IN ($placeholders)", array_merge([self::PLUGIN], array_keys(self::HOOKS)), '', true, $this->connection); + $realms = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_realms WHERE plugin = ?', [self::PLUGIN], '', true, $this->connection); + + return $hooks === count(self::HOOKS) && $realms === count(Pages::realms()); + } + + /** + * Stop Cacti from dropping the plugin tables on uninstall, and keep the + * schema version so a reinstall reuses them. + */ + public function untrackTables(): void { + db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", [self::PLUGIN], true, $this->connection); + } + + public function forgetVersion(): void { + db_execute_prepared('DELETE FROM settings WHERE name = ?', [self::SETTING], true, $this->connection); + } + + /** + * @return array schema version => migration + */ + private function migrations(): array { + return [ + 1 => fn (): bool => $this->createTables(self::tables()), + ]; + } + + /** + * Track every existing plugin table for uninstall again. + * + * Core records a table only when it creates one, so tables kept through an + * uninstall would otherwise never be dropped by a later one. The row is + * the one api_plugin_db_table_create() writes; the table has no unique + * key, so an existing row is checked for rather than replaced. + */ + public function trackTables(): void { + foreach (array_keys(self::tables()) as $table) { + if ($this->tableExists($table)) { + db_execute_prepared("INSERT INTO plugin_db_changes (plugin, `table`, `column`, `method`) SELECT ?, ?, '', 'create' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM plugin_db_changes WHERE plugin = ? AND `table` = ? AND `method` = 'create')", [self::PLUGIN, $table, self::PLUGIN, $table], true, $this->connection); + } + } + } + + /** + * @param array> $tables + */ + private function createTables(array $tables): bool { + foreach ($tables as $table => $definition) { + api_plugin_db_table_create(self::PLUGIN, $table, $definition); + + if (!$this->tableExists($table)) { + Log::error(sprintf('Unable to create table %s', $table)); + + return false; + } + } + + return true; + } + + private function tableExists(string $table): bool { + return db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [$table], '', true, $this->connection) > 0; + } + + /** + * Table definitions in api_plugin_db_table_create() format. + * + * State values are stored as varchar enum values, never list positions. + * Times are Unix seconds. No table holds a secret in the clear. + * + * @return array> + */ + public static function tables(): array { + $innodb = ['type' => 'InnoDB', 'charset' => 'utf8mb4', 'collate' => 'utf8mb4_unicode_ci', 'row_format' => 'Dynamic']; + $id = static fn (string $name): array => ['name' => $name, 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false]; + $time = static fn (string $name): array => ['name' => $name, 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => '0']; + $text = static fn (string $name, int $length, string $default = ''): array => ['name' => $name, 'type' => "varchar($length)", 'NULL' => false, 'default' => $default]; + + return [ + // GPU nodes: Cacti devices an operator has registered for GPU + // monitoring. How a node is reached is decided by #7 and added + // by the collector's migration; nothing here is a command, path, + // or URL. + 'plugin_gpu_node' => $innodb + [ + 'comment' => 'Cacti devices registered as GPU nodes', + 'columns' => [ + $id('id') + ['auto_increment' => true], + $id('host_id'), + $text('admin_state', 16, 'enabled'), + $time('created_at'), + $time('updated_at'), + ], + 'primary' => 'id', + 'unique_keys' => [['name' => 'host_id', 'columns' => ['host_id']]], + ], + // One row per GPU identity, keyed by vendor and UUID (ADR 0003, + // REQ-ID-001). Index, bus ID, name, driver, and node are + // attributes that change in place (REQ-ID-002). Rows are never + // deleted by collection (REQ-ID-005). Serial numbers are not + // stored. + 'plugin_gpu_gpu' => $innodb + [ + 'comment' => 'GPU identity records', + 'columns' => [ + $id('id') + ['auto_increment' => true], + $text('vendor', 16), + $text('uuid', 96), + $id('node_id'), + ['name' => 'gpu_index', 'type' => 'int(10)', 'unsigned' => true, 'NULL' => true], + $text('pci_bus_id', 32), + $text('name', 128), + $text('driver_version', 64), + $text('tool', 32), + $text('tool_version', 64), + $text('presence', 16, 'present'), + $id('missing_count') + ['default' => '0'], + // The absent record this GPU appeared in place of (REQ-ID-003); 0 for none. + $id('replaces_gpu_id') + ['default' => '0'], + // The node this GPU was last seen at, awaiting operator confirmation (REQ-ID-004); 0 for none. + $id('pending_node_id') + ['default' => '0'], + $time('pending_since'), + $time('first_seen'), + $time('last_seen'), + ], + 'primary' => 'id', + 'unique_keys' => [['name' => 'vendor_uuid', 'columns' => ['vendor', 'uuid']]], + 'keys' => [['name' => 'node_id', 'columns' => ['node_id']]], + ], + ]; + } +} diff --git a/lib/Settings.php b/lib/Settings.php new file mode 100644 index 0000000..aaca644 --- /dev/null +++ b/lib/Settings.php @@ -0,0 +1,88 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Plugin settings, read once per request from Cacti's settings table + * (REQ-UI-003). Collection settings arrive with the collector. + */ +final readonly class Settings { + public const NAMES = [ + 'gpu_absent_after', + 'gpu_uninstall_keep_tables', + ]; + + public const DEFAULT_ABSENT_AFTER = 3; + public const MAX_ABSENT_AFTER = 100; + + public function __construct( + public int $absentAfter, + public bool $keepTablesOnUninstall, + ) { + } + + /** + * A setting that was never saved reads as its default. Keeping tables is + * the default, so an uninstall drops node and GPU records only after an + * administrator has cleared the box (REQ-LIFE-004). + * + * @param array $row setting name => stored value, absent when never saved + */ + public static function fromRow(array $row): self { + return new self( + absentAfter: min(Row::int($row, 'gpu_absent_after', self::DEFAULT_ABSENT_AFTER, 1), self::MAX_ABSENT_AFTER), + keepTablesOnUninstall: array_key_exists('gpu_uninstall_keep_tables', $row) ? Row::bool($row, 'gpu_uninstall_keep_tables') : true, + ); + } + + /** + * Settings tab definition for the config_settings hook. + * + * @return array> + */ + public static function form(): array { + return [ + 'gpu_header_identity' => [ + 'friendly_name' => __('GPU Identity', 'gpu'), + 'method' => 'spacer', + ], + 'gpu_absent_after' => [ + 'friendly_name' => __('Mark Absent After', 'gpu'), + 'description' => __('Consecutive successful collections that must miss a GPU before it is marked absent, from 1 to 100. A failed collection, or one that reports no GPUs, never counts. Absent GPUs keep their records and history and are never deleted automatically.', 'gpu'), + 'method' => 'textbox', + 'default' => (string) self::DEFAULT_ABSENT_AFTER, + 'filter' => FILTER_VALIDATE_INT, + 'options' => ['options' => ['min_range' => 1, 'max_range' => self::MAX_ABSENT_AFTER]], + 'max_length' => '3', + 'size' => '3', + ], + 'gpu_header_uninstall' => [ + 'friendly_name' => __('Uninstall', 'gpu'), + 'method' => 'spacer', + ], + 'gpu_uninstall_keep_tables' => [ + 'friendly_name' => __('Keep Plugin Tables on Uninstall', 'gpu'), + 'description' => __('When checked, uninstalling the plugin keeps its node and GPU records. Clear it to have the uninstall drop them; export them first from GPU Nodes. Cacti devices, data sources, graphs, and RRD files are never touched either way.', 'gpu'), + 'method' => 'checkbox', + 'default' => 'on', + ], + ]; + } +} diff --git a/lib/SettingsRepository.php b/lib/SettingsRepository.php new file mode 100644 index 0000000..00bcaac --- /dev/null +++ b/lib/SettingsRepository.php @@ -0,0 +1,45 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Reads the plugin settings straight from Cacti's settings table. + * + * read_config_option() substitutes a form default for a setting that was + * never saved, and only when the config_settings hook has run in this + * request, which the poller does not do. Reading the rows keeps "never + * saved" distinguishable from "saved empty", so Settings::fromRow() applies + * the same defaults everywhere. + */ +final class SettingsRepository { + public function __construct(private readonly \PDO|false $connection) { + } + + public function load(): Settings { + $placeholders = implode(', ', array_fill(0, count(Settings::NAMES), '?')); + $row = []; + + foreach (Row::rows(db_fetch_assoc_prepared("SELECT name, value FROM settings WHERE name IN ($placeholders)", Settings::NAMES, true, $this->connection)) as $setting) { + $row[Row::string($setting, 'name')] = $setting['value'] ?? null; + } + + return Settings::fromRow($row); + } +} diff --git a/lib/SystemClock.php b/lib/SystemClock.php new file mode 100644 index 0000000..aa2c6e8 --- /dev/null +++ b/lib/SystemClock.php @@ -0,0 +1,26 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +final class SystemClock implements Clock { + public function now(): int { + return time(); + } +} diff --git a/locales/build_gettext.sh b/locales/build_gettext.sh new file mode 100755 index 0000000..3d5d031 --- /dev/null +++ b/locales/build_gettext.sh @@ -0,0 +1,111 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_gpu, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_gpu +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. +# +# Regenerate locales/po/cacti.pot from every PHP file at depth 2 or less, the +# scan the Cacti plugin gettext builds use, merge it into each catalog +# locales/po/.po, and compile each catalog to +# locales/LC_MESSAGES/.mo, where Cacti loads plugin translations. +# +# With --check, change nothing and fail when the template is out of date, a +# catalog misses or has a fuzzy entry, a format string does not match, or a +# compiled catalog differs from its source. + +set -eu + +BASE_PATH=$(cd "$(dirname "$0")/.." && pwd) +POT=locales/po/cacti.pot + +cd "$BASE_PATH" +mkdir -p locales/po + +command -v xgettext >/dev/null 2>&1 || { echo "ERROR: Unable to locate xgettext (install GNU gettext)" >&2; exit 1; } + +VERSION=$(sed -n 's/^version *= *//p' INFO) + +generate() { + # shellcheck disable=SC2046 + xgettext --no-wrap --add-location=file --from-code=UTF-8 --copyright-holder="Thomas Vincent" \ + --package-name="gpu" --package-version="$VERSION" --msgid-bugs-address="https://github.com/somethingwithproof/plugin_gpu/issues" \ + -F -L PHP -k__gettext -k__ -k__n:1,2 -k__x:1c,2 -k__xn:1c,2,3 -k__esc -k__esc_n:1,2 -k__esc_x:1c,2 -k__esc_xn:1c,2,3 -k__date \ + -o "$1" $(find . -maxdepth 2 -name '*.php' -not -path './tests/*' | sort) + + sed -e 's/FULL NAME /Thomas Vincent /' \ + -e 's/LANGUAGE /Thomas Vincent /' \ + -e 's/CHARSET/UTF-8/' \ + -e '/^"POT-Creation-Date:/d' "$1" > "$1.tmp" && mv "$1.tmp" "$1" +} + +if [ "${1:-}" = "--check" ]; then + tmp=$(mktemp) + generate "$tmp" + + if ! diff -u "$POT" "$tmp"; then + rm -f "$tmp" + echo "ERROR: $POT is out of date; run locales/build_gettext.sh and commit the result" >&2 + exit 1 + fi + + rm -f "$tmp" + echo "$POT is up to date" + + command -v msgunfmt >/dev/null 2>&1 || { echo "ERROR: Unable to locate msgunfmt (install GNU gettext)" >&2; exit 1; } + rc=0 + + for po in locales/po/*.po; do + [ -f "$po" ] || continue + locale=$(basename "$po" .po) + mo=locales/LC_MESSAGES/$locale.mo + + # Every template entry translated, none fuzzy, formats intact. + msgfmt --check -o /dev/null "$po" || { echo "ERROR: $po does not compile" >&2; rc=1; continue; } + msgcmp "$po" "$POT" || { echo "ERROR: $po misses entries of $POT; run locales/build_gettext.sh" >&2; rc=1; } + [ -z "$(msgattrib --only-fuzzy --no-obsolete "$po")" ] || { echo "ERROR: $po has fuzzy entries" >&2; rc=1; } + [ -z "$(msgattrib --untranslated --no-obsolete "$po")" ] || { echo "ERROR: $po has untranslated entries" >&2; rc=1; } + + # Cacti's __() formats a message only when it holds a plain placeholder + # (%d, %s, ...); a positional one (%1$d) is printed literally, so + # translations keep the message's argument order. + # --no-wrap keeps each msgstr on one line, so a long translation's + # continuation lines are checked too. + if msgattrib --no-obsolete --no-wrap "$po" | grep -E '^msgstr' | grep -qE '%[0-9]+\$'; then + echo "ERROR: $po uses a positional placeholder such as %1\$d, which Cacti prints literally" >&2 + rc=1 + fi + + # The compiled catalog holds the same messages as its source; compared + # decompiled, because gettext versions lay the binary out differently. + if [ ! -f "$mo" ] || [ "$(msgunfmt "$mo")" != "$(msgfmt -o - "$po" | msgunfmt)" ]; then + echo "ERROR: $mo is missing or out of date; run locales/build_gettext.sh" >&2 + rc=1 + fi + done + + [ $rc -eq 0 ] && echo "catalogs are complete and compiled" + exit $rc +fi + +generate "$POT" +echo "Updated $POT" + +mkdir -p locales/LC_MESSAGES + +for po in locales/po/*.po; do + [ -f "$po" ] || continue + msgmerge --quiet --update --no-wrap --backup=none "$po" "$POT" + msgfmt -o "locales/LC_MESSAGES/$(basename "$po" .po).mo" "$po" + echo "Compiled $po" +done diff --git a/locales/index.php b/locales/index.php new file mode 100644 index 0000000..102f0ad --- /dev/null +++ b/locales/index.php @@ -0,0 +1,20 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +header('Location: ../index.php'); diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot new file mode 100644 index 0000000..161be61 --- /dev/null +++ b/locales/po/cacti.pot @@ -0,0 +1,79 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR Thomas Vincent +# This file is distributed under the same license as the gpu package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: gpu 0.1.0-dev\n" +"Report-Msgid-Bugs-To: https://github.com/somethingwithproof/plugin_gpu/issues\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: Thomas Vincent \n" +"Language-Team: Thomas Vincent \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: lib/Pages.php +msgid "GPU View" +msgstr "" + +#: lib/Pages.php +msgid "GPU Admin" +msgstr "" + +#: lib/Pages.php +msgid "GPU Nodes" +msgstr "" + +#: lib/Pages.php +msgid "GPU Inventory" +msgstr "" + +#: lib/Settings.php +msgid "GPU Identity" +msgstr "" + +#: lib/Settings.php +msgid "Mark Absent After" +msgstr "" + +#: lib/Settings.php +msgid "Consecutive successful collections that must miss a GPU before it is marked absent, from 1 to 100. A failed collection, or one that reports no GPUs, never counts. Absent GPUs keep their records and history and are never deleted automatically." +msgstr "" + +#: lib/Settings.php +msgid "Uninstall" +msgstr "" + +#: lib/Settings.php +msgid "Keep Plugin Tables on Uninstall" +msgstr "" + +#: lib/Settings.php +msgid "When checked, uninstalling the plugin keeps its node and GPU records. Clear it to have the uninstall drop them; export them first from GPU Nodes. Cacti devices, data sources, graphs, and RRD files are never touched either way." +msgstr "" + +#: setup.php +#, php-format +msgid "The GPU plugin requires PHP %s or later. This server runs PHP %s, so the plugin was not installed or enabled." +msgstr "" + +#: setup.php +msgid "GPU" +msgstr "" + +#: setup.php +msgid "The GPU plugin is not enabled." +msgstr "" + +#: setup.php +#, php-format +msgid "The GPU plugin requires PHP %s or later." +msgstr "" + +#: setup.php +msgid "Management" +msgstr "" diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..64244ef --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_gpu, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_gpu +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. + +# Static analysis of the plugin classes against a Cacti core checkout. +# CACTI_PATH=/path/to/cacti phpstan analyse -c phpstan.neon +# Core is scanned for symbols only. +parameters: + level: 9 + phpVersion: 80200 + paths: + - lib + - setup.php + - include/unbooted-uninstall.php + scanDirectories: + - %env.CACTI_PATH%/lib + - %env.CACTI_PATH%/include + bootstrapFiles: + - tests/phpstan-bootstrap.php + excludePaths: + analyseAndScan: + - %env.CACTI_PATH%/include/vendor/* + - %env.CACTI_PATH%/include/fa/* + - %env.CACTI_PATH%/include/js/* + - %env.CACTI_PATH%/include/themes/* + treatPhpDocTypesAsCertain: false diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..45e9a44 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,28 @@ + + + + + + + + + tests/Security + tests/Unit + + + + + lib + + + diff --git a/setup.php b/setup.php new file mode 100644 index 0000000..d82fb77 --- /dev/null +++ b/setup.php @@ -0,0 +1,269 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Cacti includes this file on every request, on whatever PHP version the site + * runs. It must parse on PHP 8.0 (CI lints it there), and nothing under lib/ + * is loaded until gpu_boot() has confirmed PHP 8.2 or later (ADR 0006). + * Every hook and lifecycle function therefore starts with that check, so an + * unsupported runtime gets a refusal instead of a parse error that would take + * down the whole Cacti UI. + */ + +function gpu_php_supported(): bool { + return version_compare(PHP_VERSION, '8.2.0', '>='); +} + +function gpu_boot(): bool { + if (!gpu_php_supported()) { + return false; + } + + require_once(__DIR__ . '/include/autoload.php'); + + return true; +} + +/** + * Refuse with a message naming the required version (REQ-COMPAT-002). + * + * Used by the lifecycle functions only. Hook shims return silently instead, + * because they run on every page and a refused plugin must not flood the log. + */ +function gpu_refuse_unsupported(): bool { + if (gpu_php_supported()) { + return false; + } + + $message = __('The GPU plugin requires PHP %s or later. This server runs PHP %s, so the plugin was not installed or enabled.', '8.2.0', PHP_VERSION, 'gpu'); + + cacti_log('ERROR: ' . $message, false, 'GPU'); + + if (PHP_SAPI === 'cli') { + fwrite(STDERR, $message . PHP_EOL); + } elseif (function_exists('raise_message')) { + raise_message('gpu_php', $message, MESSAGE_LEVEL_ERROR); + } + + return true; +} + +/** + * @return array + */ +function plugin_gpu_version(): array { + $info = parse_ini_file(__DIR__ . '/INFO', true); + + if (!is_array($info) || !isset($info['info']) || !is_array($info['info'])) { + return array(); + } + + $version = array(); + + foreach ($info['info'] as $key => $value) { + $version[(string) $key] = is_scalar($value) ? (string) $value : ''; + } + + return $version; +} + +function plugin_gpu_install(): void { + if (gpu_refuse_unsupported()) { + return; + } + + plugin_gpu_upgrade(true); +} + +function plugin_gpu_check_config(): bool { + if (gpu_refuse_unsupported()) { + return false; + } + + return plugin_gpu_upgrade(true); +} + +/** + * Common start of every page script, after include/auth.php has authorized + * the realm. Refuses on an unsupported runtime or a disabled plugin, because + * Cacti keeps plugin realms registered while a plugin is disabled. + */ +function gpu_page_start(): bool { + if (gpu_boot() && api_plugin_is_enabled('gpu')) { + return true; + } + + top_header(); + + html_start_box(__('GPU', 'gpu'), '100%', '', '3', 'center', ''); + + print '' . html_escape(gpu_php_supported() ? __('The GPU plugin is not enabled.', 'gpu') : __('The GPU plugin requires PHP %s or later.', '8.2.0', 'gpu')) . ''; + + html_end_box(); + + bottom_footer(); + + return false; +} + +/** + * State-changing actions are accepted only as POST, where csrf-magic checks + * the token (REQ-UI-004). A GET that names one is sent back to the page + * without effect. + * + * @param list $actions + */ +function gpu_require_post(string $page, array $actions): void { + $action = (string) get_nfilter_request_var('action'); + + if (in_array($action, $actions, true) && $_SERVER['REQUEST_METHOD'] !== 'POST') { + header('Location: ' . $page); + exit; + } +} + +function gpu_settings(): \Somethingwithproof\Gpu\Settings { + return (new \Somethingwithproof\Gpu\SettingsRepository(false))->load(); +} + +/** + * Bring the schema, hooks, and realms up to the code's version. + * + * Cacti 1.2.31 never calls this itself; check_config and the config_arrays + * hook do. Fresh installs take the same path as upgrades. The version stored + * in plugin_config changes only after every migration has succeeded, so an + * interrupted run is finished by the next one (REQ-LIFE-002). + * + * $grant gives newly registered realms to the current user. Only install and + * check_config pass it: both run from the Plugins page, which needs plugin + * management. A repair triggered from config_arrays can run for anyone who + * opens a plugin page, so it must never grant anything. + */ +function plugin_gpu_upgrade(bool $grant = false): bool { + if (!gpu_boot()) { + return false; + } + + $info = plugin_gpu_version(); + $schema = new \Somethingwithproof\Gpu\Schema(false); + + if ($schema->isCurrent() && $schema->recordedPluginVersion() === $info['version'] && $schema->hooksRegistered()) { + return true; + } + + if (!$schema->migrate()) { + return false; + } + + $schema->trackTables(); + + gpu_setup_hooks($grant); + + $schema->recordPluginVersion($info['version'], $info['author'], $info['homepage']); + + return true; +} + +/** + * Register hooks and realms. + * + * Kept procedural and named *_setup_* because api_plugin_register_hook() and + * api_plugin_register_realm() refuse callers whose function name does not + * contain install, upgrade, or setup. + */ +function gpu_setup_hooks(bool $grant = false): void { + global $config; + + // Registering a hook replicates plugin config, which needs core lib/poller.php. + if (!function_exists('replicate_out')) { + include_once($config['library_path'] . '/poller.php'); + } + + foreach (\Somethingwithproof\Gpu\Schema::HOOKS as $hook => $function) { + api_plugin_register_hook('gpu', $hook, $function, 'setup.php'); + } + + foreach (\Somethingwithproof\Gpu\Pages::realms() as $realm) { + api_plugin_register_realm('gpu', implode(',', $realm['files']), $realm['name'], $grant); + } +} + +/** + * Uninstall never touches a Cacti device, data source, graph, or RRD file, + * and never contacts a GPU node (REQ-LIFE-004, REQ-LIFE-005). Core drops the + * tracked plugin tables afterwards unless the administrator left "Keep + * Plugin Tables on Uninstall" checked, which is the default. + */ +function plugin_gpu_uninstall(): void { + if (!gpu_boot()) { + include_once(__DIR__ . '/include/unbooted-uninstall.php'); + gpu_uninstall_unbooted(); + + return; + } + + $schema = new \Somethingwithproof\Gpu\Schema(false); + + if (gpu_settings()->keepTablesOnUninstall) { + $schema->untrackTables(); + + \Somethingwithproof\Gpu\Log::info('Uninstall kept the plugin tables as configured'); + } else { + $schema->forgetVersion(); + } +} + +function gpu_config_arrays(): void { + global $menu; + + if (!gpu_boot()) { + return; + } + + foreach (\Somethingwithproof\Gpu\Pages::menu() as $file => $title) { + $menu[__('Management')]['plugins/gpu/' . $file] = $title; + } + + if (in_array(get_current_page(), \Somethingwithproof\Gpu\Pages::upgradeTriggers(), true)) { + plugin_gpu_upgrade(); + } +} + +function gpu_config_settings(): void { + global $tabs, $settings; + + if (!gpu_boot()) { + return; + } + + $tabs['gpu'] = __('GPU', 'gpu'); + $settings['gpu'] = \Somethingwithproof\Gpu\Settings::form(); +} + +/** + * @param array $nav + * @return array + */ +function gpu_draw_navigation_text($nav) { + if (!gpu_boot()) { + return $nav; + } + + return array_merge($nav, \Somethingwithproof\Gpu\Pages::navigation()); +} diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..068112a --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,22 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Pest configuration. Bootstraps are named by phpunit.xml. + */ diff --git a/tests/Security/SourceRulesTest.php b/tests/Security/SourceRulesTest.php new file mode 100644 index 0000000..df05d97 --- /dev/null +++ b/tests/Security/SourceRulesTest.php @@ -0,0 +1,302 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Source rules from docs/PLAN.md "Code structure" and ADR 0006 that a parser + * can check. The PHP 8.0 parse of the entry points themselves is proven by the + * CI lint job on a real PHP 8.0; these checks catch the same mistakes earlier + * and cover the rules a lint cannot. + */ + +function gpu_root(): string { + return dirname(__DIR__, 2); +} + +/** + * @return list plugin PHP files outside tests/, relative to the root + */ +function gpu_sources(): array { + $files = []; + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(gpu_root(), FilesystemIterator::SKIP_DOTS)); + + foreach ($iterator as $file) { + $relative = substr($file->getPathname(), strlen(gpu_root()) + 1); + + if ($file->getExtension() === 'php' && !str_starts_with($relative, 'tests/') && !str_starts_with($relative, '.git/')) { + $files[] = $relative; + } + } + + sort($files); + + return $files; +} + +/** + * @return list files Cacti may include before the PHP version check + */ +function gpu_entry_points(): array { + return array_values(array_filter(gpu_sources(), fn (string $f) => !str_starts_with($f, 'lib/'))); +} + +it('keeps every PHP source file within the gettext scan depth', function () { + foreach (gpu_sources() as $file) { + expect(substr_count($file, '/'))->toBeLessThanOrEqual(1, $file); + } +}); + +it('keeps entry points free of PHP 8.1 and later syntax', function () { + $banned = [T_ENUM => 'enum', T_READONLY => 'readonly']; + + foreach (gpu_entry_points() as $file) { + $tokens = PhpToken::tokenize((string) file_get_contents(gpu_root() . '/' . $file)); + + foreach ($tokens as $i => $token) { + expect(isset($banned[$token->id]))->toBeFalse("$file:{$token->line} uses {$token->text}"); + + // "never" as a return type and "new" in an initializer are 8.1. + if ($token->is(T_STRING) && strtolower($token->text) === 'never') { + $previous = $tokens[$i - 1]->is(T_WHITESPACE) ? $tokens[$i - 2] : $tokens[$i - 1]; + expect($previous->text)->not->toBe(':', "$file:{$token->line} uses never"); + } + } + } +}); + +it('uses no PHP 8.3 or later features anywhere', function () { + foreach (gpu_sources() as $file) { + $source = (string) file_get_contents(gpu_root() . '/' . $file); + $tokens = PhpToken::tokenize($source); + + expect($source)->not->toContain('json_validate(') + ->and($source)->not->toContain('#[\\Override]') + ->and($source)->not->toContain('#[Override]'); + + foreach ($tokens as $i => $token) { + if (!$token->is(T_CONST)) { + continue; + } + + // A typed constant has two identifiers between const and "=". + $names = 0; + + for ($j = $i + 1; $j < count($tokens) && $tokens[$j]->text !== '='; $j++) { + $names += $tokens[$j]->is(T_STRING) ? 1 : 0; + } + + expect($names)->toBe(1, "$file:{$token->line} declares a typed constant"); + } + } +}); + +it('defines exactly one class, interface, or enum per lib file, named after the file', function () { + foreach (glob(gpu_root() . '/lib/*.php') as $path) { + $tokens = PhpToken::tokenize((string) file_get_contents($path)); + $names = []; + + foreach ($tokens as $i => $token) { + if ($token->is([T_CLASS, T_INTERFACE, T_ENUM, T_TRAIT]) && !$tokens[$i - 1]->is(T_DOUBLE_COLON)) { + $next = $tokens[$i + 1]->is(T_WHITESPACE) ? $tokens[$i + 2] : $tokens[$i + 1]; + + if ($next->is(T_STRING)) { + $names[] = $next->text; + } + } + } + + expect($names)->toBe([basename($path, '.php')], basename($path)) + ->and((string) file_get_contents($path))->toContain("namespace Somethingwithproof\\Gpu;"); + } +}); + +it('keeps lib classes away from request variables and globals', function () { + foreach (glob(gpu_root() . '/lib/*.php') as $path) { + $source = (string) file_get_contents($path); + + expect($source)->not->toMatch('/\$_(REQUEST|GET|POST|SESSION|SERVER|COOKIE)\b/', basename($path)) + ->and($source)->not->toMatch('/\bglobal\s+\$/', basename($path)) + ->and($source)->not->toContain('$GLOBALS', basename($path)); + } +}); + +it('issues SQL only from repository and schema classes, through prepared helpers', function () { + foreach (gpu_sources() as $file) { + $source = (string) file_get_contents(gpu_root() . '/' . $file); + + expect($source)->not->toMatch('/\bdb_(execute|fetch_cell|fetch_row|fetch_assoc)\s*\(/', $file); + + // include/unbooted-uninstall.php is the one exception: it runs where + // lib/ cannot load (see its header). + $repository = str_starts_with($file, 'lib/') && preg_match('/^(Schema|\w+Repository)\.php$/', basename($file)) === 1; + + if (!$repository && $file !== 'include/unbooted-uninstall.php') { + expect($source)->not->toMatch('/\bdb_\w+_prepared\s*\(/', $file); + } + } +}); + +it('passes the gpu text domain to every translated plugin string', function () { + // Labels intentionally reused from core keep the core domain. + $core = ['Management']; + + foreach (gpu_sources() as $file) { + $tokens = array_values(array_filter(PhpToken::tokenize((string) file_get_contents(gpu_root() . '/' . $file)), fn ($t) => !$t->is([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT]))); + + foreach ($tokens as $i => $token) { + if (!$token->is(T_STRING) || $token->text !== '__' || ($tokens[$i + 1]->text ?? '') !== '(' || ($tokens[$i - 1]->is(T_FUNCTION))) { + continue; + } + + $depth = 0; + $last = null; + + for ($j = $i + 1; $j < count($tokens); $j++) { + $depth += $tokens[$j]->text === '(' ? 1 : ($tokens[$j]->text === ')' ? -1 : 0); + + if ($depth === 0) { + break; + } + + if ($depth === 1 && $tokens[$j]->text !== ',' && $tokens[$j]->text !== '(') { + $last = $tokens[$j]; + } + } + + $first = $tokens[$i + 2]; + + if ($first->is(T_CONSTANT_ENCAPSED_STRING) && in_array(trim($first->text, '\'"'), $core, true)) { + continue; + } + + expect($last?->text)->toBe("'gpu'", "$file:{$token->line}"); + } + } +}); + +it('ships a translation template containing every plugin string', function () { + $pot = (string) file_get_contents(gpu_root() . '/locales/po/cacti.pot'); + + foreach (['The GPU plugin requires PHP %s or later. This server runs PHP %s, so the plugin was not installed or enabled.'] as $msgid) { + expect($pot)->toContain('msgid "' . $msgid . '"'); + } +}); + +it('formats translated strings with __() itself, never sprintf(__())', function () { + // Core's __() hands the text domain to sprintf(), so a placeholder in + // sprintf(__("%d", "gpu"), $n) takes "gpu" and prints 0 or the + // domain. The values go inside the call: __("%d", $n, "gpu"). + foreach (gpu_sources() as $file) { + expect((string) file_get_contents(gpu_root() . '/' . $file))->not->toContain('sprintf(__(', $file); + } +}); + +it('uses plain placeholders in translated strings, because core\'s __() does not format positional ones', function () { + // __() only formats a string that has %d, %s, and the like. A string with + // only %1$d placeholders comes back raw. + foreach (gpu_sources() as $file) { + $source = (string) file_get_contents(gpu_root() . '/' . $file); + + preg_match_all("/__\\('((?:[^'\\\\]|\\\\.)*)'/", $source, $texts); + + foreach ($texts[1] as $text) { + expect($text)->not->toMatch('/%[0-9]+\$/', $file); + } + } +}); + +it('logs through cacti_log() under the GPU tag only', function () { + foreach (gpu_sources() as $file) { + $code = ''; + + foreach (PhpToken::tokenize((string) file_get_contents(gpu_root() . '/' . $file)) as $token) { + $code .= $token->is([T_COMMENT, T_DOC_COMMENT]) ? '' : $token->text; + } + + preg_match_all('/\bcacti_log\s*\((.*?)\);/s', $code, $calls); + + foreach ($calls[1] as $arguments) { + expect(str_contains($arguments, "'GPU'"))->toBeTrue($file); + } + } +}); + +it('ships no Composer runtime dependencies', function () { + $manifest = gpu_root() . '/composer.json'; + + if (is_file($manifest)) { + $require = json_decode((string) file_get_contents($manifest), true)['require'] ?? []; + + foreach (array_keys($require) as $package) { + expect($package === 'php' || str_starts_with($package, 'ext-'))->toBeTrue($package); + } + } + + expect(is_dir(gpu_root() . '/vendor'))->toBeFalse(); +}); + +it('reads request variables only through Cacti\'s accessors', function () { + // REQ-UI-002. $_SERVER is allowed for the request method alone. + foreach (gpu_sources() as $file) { + $source = (string) file_get_contents(gpu_root() . '/' . $file); + + expect($source)->not->toMatch('/\$_(REQUEST|GET|POST|COOKIE|FILES)\b/', $file); + + preg_match_all('/\$_SERVER\[\'([A-Z_]+)\'\]/', $source, $keys); + + expect(array_values(array_diff($keys[1], ['REQUEST_METHOD'])))->toBe([], $file); + } +}); + +it('starts no process: milestone 2 runs no command on any host', function () { + // REQ-LIFE-005 and ADR 0007. The command runner arrives with collection + // in milestone 3; until then nothing may run a program at all. + $banned = ['exec', 'shell_exec', 'system', 'passthru', 'proc_open', 'popen', 'pcntl_exec', 'exec_background']; + + foreach (gpu_sources() as $file) { + $tokens = array_values(array_filter(PhpToken::tokenize((string) file_get_contents(gpu_root() . '/' . $file)), fn ($t) => !$t->is([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT]))); + + foreach ($tokens as $i => $token) { + expect($token->text)->not->toBe('`', "$file:{$token->line} uses a backtick command"); + + if ($token->is(T_STRING) && in_array(strtolower($token->text), $banned, true) && ($tokens[$i + 1]->text ?? '') === '(' && !($tokens[$i - 1]->is([T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_FUNCTION]))) { + expect(false)->toBeTrue("$file:{$token->line} calls {$token->text}()"); + } + } + } +}); + +it('names no state-changing vendor command anywhere', function () { + // REQ-LIFE-005: clocks, power limits, persistence mode, resets, MIG + // layout, and amd-smi set or reset are never invoked. A string that + // pairs a vendor tool with one of these is refused wherever it appears. + $mutating = '/\b(nvidia-smi|dcgmi|amd-smi|rocm-smi)\b.*(\s-(pm|pl|ac|rac|lgc|rgc|lmc|rmc|r|e|c|mig|cgi|cci|dgi|dci)\b|--(persistence-mode|power-limit|applications-clocks|reset-applications-clocks|lock-gpu-clocks|reset-gpu-clocks|lock-memory-clocks|reset-memory-clocks|gpu-reset|ecc-config|compute-mode|multi-instance-gpu)\b|\s(mig|set|reset|config)\s)/i'; + + foreach (gpu_sources() as $file) { + foreach (PhpToken::tokenize((string) file_get_contents(gpu_root() . '/' . $file)) as $token) { + if ($token->is([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE])) { + expect($token->text)->not->toMatch($mutating, "$file:{$token->line}"); + } + } + } + + expect(preg_match($mutating, "'nvidia-smi -pl 200'"))->toBe(1) + ->and(preg_match($mutating, "'nvidia-smi --gpu-reset -i 0'"))->toBe(1) + ->and(preg_match($mutating, "'amd-smi set --power-cap 100'"))->toBe(1) + ->and(preg_match($mutating, "'nvidia-smi --query-gpu=uuid,index --format=csv'"))->toBe(0); +}); diff --git a/tests/Unit/BootTest.php b/tests/Unit/BootTest.php new file mode 100644 index 0000000..5737def --- /dev/null +++ b/tests/Unit/BootTest.php @@ -0,0 +1,64 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Gpu\Log; + +beforeEach(function () { + $GLOBALS['__gpu_log'] = []; +}); + +it('reads its metadata from INFO', function () { + $info = plugin_gpu_version(); + + expect($info['name'])->toBe('gpu') + ->and($info['compat'])->toBe('1.2.31') + // Nothing is collected before milestone 3, and remote collectors are phase 3. + ->and($info['capabilities'])->not->toContain('remote_collect') + ->and($info['capabilities'])->not->toContain('remote_poller'); +}); + +it('boots and loads plugin classes on a supported runtime', function () { + expect(gpu_php_supported())->toBeTrue() + ->and(gpu_boot())->toBeTrue() + ->and(class_exists(Log::class))->toBeTrue(); +}); + +it('does not refuse or log on a supported runtime', function () { + expect(gpu_refuse_unsupported())->toBeFalse() + ->and($GLOBALS['__gpu_log'])->toBe([]); +}); + +it('ignores classes outside its namespace and nested names', function () { + expect(class_exists('Somethingwithproof\\Gpu\\Nested\\Log'))->toBeFalse() + ->and(class_exists('Somethingwithproof\\GpuLog'))->toBeFalse(); +}); + +it('logs under the GPU tag at the right verbosity', function () { + Log::debug('d'); + Log::info('i'); + Log::warning('w'); + Log::error('e'); + + expect($GLOBALS['__gpu_log'])->toBe([ + ['message' => 'DEBUG: d', 'environ' => 'GPU', 'level' => POLLER_VERBOSITY_DEBUG], + ['message' => 'NOTE: i', 'environ' => 'GPU', 'level' => POLLER_VERBOSITY_MEDIUM], + ['message' => 'WARNING: w', 'environ' => 'GPU', 'level' => ''], + ['message' => 'ERROR: e', 'environ' => 'GPU', 'level' => ''], + ]); +}); diff --git a/tests/Unit/LifecycleUnitTest.php b/tests/Unit/LifecycleUnitTest.php new file mode 100644 index 0000000..3b08d16 --- /dev/null +++ b/tests/Unit/LifecycleUnitTest.php @@ -0,0 +1,108 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Gpu\Pages; +use Somethingwithproof\Gpu\Schema; +use Somethingwithproof\Gpu\Settings; + +it('applies documented defaults to settings that were never saved', function () { + $settings = Settings::fromRow([]); + + expect($settings->absentAfter)->toBe(Settings::DEFAULT_ABSENT_AFTER) + ->and($settings->keepTablesOnUninstall)->toBeTrue(); +}); + +it('drops tables on uninstall only after the box was cleared and saved', function () { + expect(Settings::fromRow(['gpu_uninstall_keep_tables' => ''])->keepTablesOnUninstall)->toBeFalse() + ->and(Settings::fromRow(['gpu_uninstall_keep_tables' => null])->keepTablesOnUninstall)->toBeFalse() + ->and(Settings::fromRow(['gpu_uninstall_keep_tables' => 'on'])->keepTablesOnUninstall)->toBeTrue(); +}); + +it('bounds the absent count to its documented range', function (mixed $stored, int $expected) { + expect(Settings::fromRow(['gpu_absent_after' => $stored])->absentAfter)->toBe($expected); +})->with([ + ['1', 1], + ['5', 5], + ['0', Settings::DEFAULT_ABSENT_AFTER], + ['-5', Settings::DEFAULT_ABSENT_AFTER], + ['abc', Settings::DEFAULT_ABSENT_AFTER], + ['', Settings::DEFAULT_ABSENT_AFTER], + ['5000', Settings::MAX_ABSENT_AFTER], +]); + +it('gives every setting in the form a default that fromRow agrees with', function () { + $form = Settings::form(); + + foreach (Settings::NAMES as $name) { + expect($form)->toHaveKey($name); + } + + $defaults = Settings::fromRow([ + 'gpu_absent_after' => $form['gpu_absent_after']['default'], + 'gpu_uninstall_keep_tables' => $form['gpu_uninstall_keep_tables']['default'], + ]); + + expect($defaults)->toEqual(Settings::fromRow([])) + ->and($form['gpu_absent_after']['options'])->toBe(['options' => ['min_range' => 1, 'max_range' => Settings::MAX_ABSENT_AFTER]]); +}); + +it('registers the two realms the requirements name', function () { + expect(array_column(Pages::realms(), 'name'))->toBe(['GPU View', 'GPU Admin']); +}); + +it('puts every page in exactly one realm', function () { + $files = Pages::files(); + + expect($files)->toBe(array_values(array_unique($files))); + + foreach (Pages::realms() as $realm) { + expect($realm['files'])->not->toBe([]); + } +}); + +it('gives every menu page a breadcrumb under the console', function () { + $nav = Pages::navigation(); + + foreach (array_keys(Pages::menu()) as $file) { + expect($nav[$file . ':']['mapping'])->toBe('index.php:') + ->and($nav[$file . ':']['url'])->toBe($file); + } +}); + +it('names every hook function that setup.php defines', function () { + foreach (Schema::HOOKS as $function) { + expect(function_exists($function))->toBeTrue($function); + } +}); + +it('defines plugin tables with the plugin prefix, a primary key, and no serial or secret columns', function () { + foreach (Schema::tables() as $table => $definition) { + expect($table)->toStartWith('plugin_gpu_') + ->and($definition)->toHaveKey('primary') + ->and($definition['type'])->toBe('InnoDB'); + + foreach ($definition['columns'] as $column) { + expect($column['name'])->not->toMatch('/serial|token|password|secret|private_key|command|path|url/'); + } + } +}); + +it('keys GPU records by vendor and UUID only', function () { + expect(Schema::tables()['plugin_gpu_gpu']['unique_keys'])->toBe([['name' => 'vendor_uuid', 'columns' => ['vendor', 'uuid']]]); +}); diff --git a/tests/Unit/RowTest.php b/tests/Unit/RowTest.php new file mode 100644 index 0000000..4635744 --- /dev/null +++ b/tests/Unit/RowTest.php @@ -0,0 +1,108 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + + +use Somethingwithproof\Gpu\Row; + +describe('Row::int', function () { + it('reads whole decimal numbers from strings and ints', function () { + expect(Row::int(['v' => '42'], 'v'))->toBe(42) + ->and(Row::int(['v' => ' 7 '], 'v'))->toBe(7) + ->and(Row::int(['v' => '-3'], 'v'))->toBe(-3) + ->and(Row::int(['v' => 9], 'v'))->toBe(9); + }); + + it('returns the default for missing, NULL, and empty values', function () { + expect(Row::int([], 'v', 5))->toBe(5) + ->and(Row::int(['v' => null], 'v', 5))->toBe(5) + ->and(Row::int(['v' => ''], 'v', 5))->toBe(5); + }); + + it('returns the default for malformed values instead of truncating them', function (mixed $value) { + expect(Row::int(['v' => $value], 'v', 5))->toBe(5); + })->with([ + 'decimal' => '1.5', + 'exponent' => '1e3', + 'trailing text' => '12abc', + 'leading text' => 'abc12', + 'float' => 3.0, + 'bool' => true, + 'array' => [[1]], + 'too long' => '1234567890123456789012', + ]); + + it('returns the default below the minimum', function () { + expect(Row::int(['v' => '0'], 'v', 1, 1))->toBe(1) + ->and(Row::int(['v' => '-1'], 'v', 0, 0))->toBe(0) + ->and(Row::int(['v' => '1'], 'v', 9, 1))->toBe(1); + }); +}); + +describe('Row::float', function () { + it('keeps zero distinct from unknown', function () { + expect(Row::float(['v' => '0'], 'v'))->toBe(0.0) + ->and(Row::float(['v' => 0], 'v'))->toBe(0.0) + ->and(Row::float(['v' => null], 'v'))->toBeNull() + ->and(Row::float(['v' => ''], 'v'))->toBeNull() + ->and(Row::float([], 'v'))->toBeNull(); + }); + + it('reads numeric strings including rrdtool exponent notation', function () { + expect(Row::float(['v' => '1.2345000000e-02'], 'v'))->toBe(0.012345) + ->and(Row::float(['v' => ' 20 '], 'v'))->toBe(20.0); + }); + + it('treats rrdtool unknowns and malformed text as unknown', function (mixed $value) { + expect(Row::float(['v' => $value], 'v'))->toBeNull(); + })->with(['U', 'nan', 'NaN', 'inf', '-', '1,5', 'abc', [[1]], true]); + + it('treats non-finite floats as unknown', function () { + expect(Row::float(['v' => NAN], 'v'))->toBeNull() + ->and(Row::float(['v' => INF], 'v'))->toBeNull(); + }); +}); + +describe('Row::string', function () { + it('casts scalars, trims, and maps missing or NULL to empty', function () { + expect(Row::string(['v' => ' a '], 'v'))->toBe('a') + ->and(Row::string(['v' => 12], 'v'))->toBe('12') + ->and(Row::string(['v' => null], 'v'))->toBe('') + ->and(Row::string([], 'v'))->toBe('') + ->and(Row::string(['v' => ['x']], 'v'))->toBe(''); + }); +}); + +describe('Row::bool', function () { + it('accepts only explicit true spellings', function (mixed $value, bool $expected) { + expect(Row::bool(['v' => $value], 'v'))->toBe($expected); + })->with([ + 'checkbox on' => ['on', true], + 'yes' => ['yes', true], + 'YES' => [' YES ', true], + 'one string' => ['1', true], + 'one int' => [1, true], + 'true' => [true, true], + 'empty' => ['', false], + 'null' => [null, false], + 'zero' => ['0', false], + 'off' => ['off', false], + 'two' => [2, false], + 'garbage' => ['enabled', false], + ]); +}); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php new file mode 100644 index 0000000..d2aa175 --- /dev/null +++ b/tests/bootstrap-unit.php @@ -0,0 +1,172 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Unit test bootstrap. Stubs the few Cacti helpers the plugin calls, so the + * suite needs no database or Cacti checkout. Each stub records its calls in + * $GLOBALS for tests to read. + */ + +if (!defined('POLLER_VERBOSITY_MEDIUM')) { + define('POLLER_VERBOSITY_NONE', 1); + define('POLLER_VERBOSITY_LOW', 2); + define('POLLER_VERBOSITY_MEDIUM', 3); + define('POLLER_VERBOSITY_HIGH', 4); + define('POLLER_VERBOSITY_DEBUG', 5); +} + +if (!defined('MESSAGE_LEVEL_ERROR')) { + define('MESSAGE_LEVEL_ERROR', 3); +} + +$GLOBALS['__gpu_log'] = []; + +if (!function_exists('__')) { + // Core's __() (include/global_languages.php) passes every argument to + // sprintf(), the trailing text domain included, when the text has a + // placeholder. A placeholder therefore takes the domain unless the caller + // supplied values before it: __('%d s', $n, 'gpu'), never + // sprintf(__('%d s', 'gpu'), $n). + function __() { + $args = func_get_args(); + + if (count($args) === 1 || preg_match('/%(%|c|[-0-9.]*[bdeEfFgGhHosuxX])/', $args[0]) !== 1) { + return $args[0]; + } + + return call_user_func_array('sprintf', $args); + } +} + +if (!function_exists('cacti_log')) { + function cacti_log($string, $output = false, $environ = 'CMDPHP', $level = '') { + $GLOBALS['__gpu_log'][] = ['message' => $string, 'environ' => $environ, 'level' => $level]; + + return true; + } +} + +$GLOBALS['__gpu_options'] = []; + +if (!function_exists('read_config_option')) { + function read_config_option($config_name, $force = false) { + return $GLOBALS['__gpu_options'][$config_name] ?? ''; + } +} + +// Repositories in unit tests talk to these stubs. A test reads the +// statements from $GLOBALS['__gpu_db_exec'] and queues query results in +// $GLOBALS['__gpu_db_rows'] (keyed by a substring of the SQL). +$GLOBALS['__gpu_db_exec'] = []; +$GLOBALS['__gpu_db_rows'] = []; + +function gpu_test_rows(string $sql): mixed { + foreach ($GLOBALS['__gpu_db_rows'] as $needle => $rows) { + if (str_contains($sql, $needle)) { + return $rows; + } + } + + return []; +} + +if (!function_exists('db_execute_prepared')) { + function db_execute_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { + $GLOBALS['__gpu_db_exec'][] = ['sql' => $sql, 'params' => $params]; + + return true; + } +} + +if (!function_exists('db_fetch_assoc_prepared')) { + function db_fetch_assoc_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { + return gpu_test_rows($sql); + } +} + +if (!function_exists('db_fetch_row_prepared')) { + function db_fetch_row_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { + $rows = gpu_test_rows($sql); + + return is_array($rows) && isset($rows[0]) ? $rows[0] : []; + } +} + +// Transactions are recorded as BEGIN, COMMIT, and ROLLBACK statements. +// @@in_transaction answers from $GLOBALS['__gpu_in_tx'] in order, then 1, +// so a test can play InnoDB ending a transaction on a deadlock. +$GLOBALS['__gpu_in_tx'] = []; + +if (!function_exists('db_begin_transaction')) { + function db_begin_transaction($db_conn = false) { + $GLOBALS['__gpu_db_exec'][] = ['sql' => 'BEGIN', 'params' => []]; + + return true; + } + + function db_commit_transaction($db_conn = false) { + $GLOBALS['__gpu_db_exec'][] = ['sql' => 'COMMIT', 'params' => []]; + + return true; + } + + function db_rollback_transaction($db_conn = false) { + $GLOBALS['__gpu_db_exec'][] = ['sql' => 'ROLLBACK', 'params' => []]; + + return true; + } +} + +if (!function_exists('db_fetch_cell_prepared')) { + function db_fetch_cell_prepared($sql, $params = [], $col_name = '', $log = true, $db_conn = false, $log_function = null) { + if (str_contains($sql, '@@in_transaction')) { + return $GLOBALS['__gpu_in_tx'] === [] ? 1 : array_shift($GLOBALS['__gpu_in_tx']); + } + + $rows = gpu_test_rows($sql); + + return is_array($rows) && isset($rows[0]) ? reset($rows[0]) : 0; + } +} + +if (!function_exists('db_fetch_insert_id')) { + function db_fetch_insert_id($db_conn = false) { + return 1; + } +} + +// What the last write changed; a test sets it before a guarded update. +$GLOBALS['__gpu_affected_rows'] = 1; + +if (!function_exists('db_affected_rows')) { + function db_affected_rows($db_conn = false) { + return $GLOBALS['__gpu_affected_rows']; + } +} + + +$GLOBALS['config'] = [ + 'base_path' => '/var/www/cacti', + 'library_path' => '/var/www/cacti/lib', + 'poller_id' => 1, + 'is_web' => false, +]; + +require_once dirname(__DIR__) . '/setup.php'; +require_once dirname(__DIR__) . '/include/autoload.php'; diff --git a/tests/phpstan-bootstrap.php b/tests/phpstan-bootstrap.php new file mode 100644 index 0000000..af3852c --- /dev/null +++ b/tests/phpstan-bootstrap.php @@ -0,0 +1,28 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +// Constants core defines at runtime, so PHPStan can resolve them without a database. +$cacti_root = rtrim((string) getenv('CACTI_PATH'), '/'); + +if ($cacti_root === '' || !is_file($cacti_root . '/include/global_constants.php')) { + fwrite(STDERR, "Set CACTI_PATH to the Cacti root.\n"); + exit(2); +} + +require_once $cacti_root . '/include/global_constants.php'; From 7927d0bfec0572688b911c9657aba0658e2bbb30 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 00:16:55 -0800 Subject: [PATCH 03/10] feat: node registry and GPU identity records Add GPU nodes (Cacti devices registered for GPU monitoring) and GPU identity records keyed by vendor and UUID, with index, PCI bus ID, name, driver version, and the reporting tool and version stored as attributes that change in place. IdentityReconciler decides how one successful collection at one node changes the records, and GpuRepository applies the decision: - A new UUID gets its own record. If an unreported record at the same node had the same PCI bus ID, the new one is flagged as its possible replacement and inherits nothing. The match ignores the index, which can change at any boot. - A UUID seen at another node stays with its record's node and is marked as a pending move until an operator confirms or rejects it. - A GPU missing from successful collections is marked absent after a configurable count and never deleted. A disabled node, an empty result, or a failed collection changes nothing. Tool output is validated before it can reach a record: whole-GPU NVIDIA UUIDs only, normalized PCI bus IDs, control characters stripped, and a snapshot that repeats a UUID or bus ID is refused whole. MIG instance UUIDs are refused as keys, because whether a recreated instance can get a UUID back is unresolved (research/mig.md); MIG waits for #13. AMD waits for #19. Serial numbers are not stored. The unique key on (vendor, uuid) refuses a second record for one GPU even if writers race, and a node that owns GPU records cannot be deleted. Synthetic fixture sequences cover reboot reorder, card swap, slot move, driver change, a lost and a returning GPU, pending and confirmed moves, unavailable values, refused output, and a disabled node, and check that no sequence yields two records for one UUID. Refs #33 Signed-off-by: Thomas Vincent --- lib/GpuRecord.php | 157 +++++++++++++++ lib/GpuReport.php | 119 ++++++++++++ lib/GpuRepository.php | 120 ++++++++++++ lib/GpuSnapshot.php | 80 ++++++++ lib/IdentityReconciler.php | 107 ++++++++++ lib/Inventory.php | 57 ++++++ lib/InventoryExport.php | 50 +++++ lib/Node.php | 59 ++++++ lib/NodeRepository.php | 104 ++++++++++ lib/Presence.php | 30 +++ lib/Reconciliation.php | 40 ++++ lib/Vendor.php | 35 ++++ tests/Unit/GpuReportTest.php | 95 +++++++++ tests/Unit/IdentityTest.php | 182 ++++++++++++++++++ tests/Unit/RepositoryTest.php | 142 ++++++++++++++ .../identity/card-swap-reindexed.json | 74 +++++++ tests/fixtures/identity/card-swap.json | 107 ++++++++++ tests/fixtures/identity/disabled-node.json | 28 +++ tests/fixtures/identity/driver-change.json | 53 +++++ tests/fixtures/identity/gpu-returns.json | 99 ++++++++++ tests/fixtures/identity/lost-gpu.json | 93 +++++++++ .../identity/node-move-confirmed.json | 100 ++++++++++ .../fixtures/identity/node-move-pending.json | 67 +++++++ .../fixtures/identity/node-move-returns.json | 66 +++++++ tests/fixtures/identity/reboot-reorder.json | 78 ++++++++ tests/fixtures/identity/refused-output.json | 115 +++++++++++ tests/fixtures/identity/slot-move.json | 74 +++++++ .../fixtures/identity/unavailable-values.json | 35 ++++ 28 files changed, 2366 insertions(+) create mode 100644 lib/GpuRecord.php create mode 100644 lib/GpuReport.php create mode 100644 lib/GpuRepository.php create mode 100644 lib/GpuSnapshot.php create mode 100644 lib/IdentityReconciler.php create mode 100644 lib/Inventory.php create mode 100644 lib/InventoryExport.php create mode 100644 lib/Node.php create mode 100644 lib/NodeRepository.php create mode 100644 lib/Presence.php create mode 100644 lib/Reconciliation.php create mode 100644 lib/Vendor.php create mode 100644 tests/Unit/GpuReportTest.php create mode 100644 tests/Unit/IdentityTest.php create mode 100644 tests/Unit/RepositoryTest.php create mode 100644 tests/fixtures/identity/card-swap-reindexed.json create mode 100644 tests/fixtures/identity/card-swap.json create mode 100644 tests/fixtures/identity/disabled-node.json create mode 100644 tests/fixtures/identity/driver-change.json create mode 100644 tests/fixtures/identity/gpu-returns.json create mode 100644 tests/fixtures/identity/lost-gpu.json create mode 100644 tests/fixtures/identity/node-move-confirmed.json create mode 100644 tests/fixtures/identity/node-move-pending.json create mode 100644 tests/fixtures/identity/node-move-returns.json create mode 100644 tests/fixtures/identity/reboot-reorder.json create mode 100644 tests/fixtures/identity/refused-output.json create mode 100644 tests/fixtures/identity/slot-move.json create mode 100644 tests/fixtures/identity/unavailable-values.json diff --git a/lib/GpuRecord.php b/lib/GpuRecord.php new file mode 100644 index 0000000..d7c0124 --- /dev/null +++ b/lib/GpuRecord.php @@ -0,0 +1,157 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * A GPU identity record. Its key is vendor and UUID and never changes; every + * other field describes the GPU's current state (REQ-ID-002) and is replaced + * through the transitions below, which IdentityReconciler chooses. + */ +final readonly class GpuRecord { + public function __construct( + // 0 until the record is first stored. + public int $id, + public Vendor $vendor, + public string $uuid, + public int $nodeId, + public ?int $index, + public string $pciBusId, + public string $name, + public string $driverVersion, + // The tool and version that last reported this GPU (REQ-ID-006). + public string $tool, + public string $toolVersion, + public Presence $presence, + public int $missingCount, + public int $replacesGpuId, + public int $pendingNodeId, + public int $pendingSince, + public int $firstSeen, + public int $lastSeen, + ) { + } + + /** + * @param array $row a plugin_gpu_gpu row + */ + public static function fromRow(array $row): ?self { + $vendor = Vendor::tryFrom(Row::string($row, 'vendor')); + + if ($vendor === null) { + return null; + } + + $index = $row['gpu_index'] ?? null; + + return new self( + id: Row::int($row, 'id'), + vendor: $vendor, + uuid: Row::string($row, 'uuid'), + nodeId: Row::int($row, 'node_id'), + index: $index === null || $index === '' ? null : Row::int($row, 'gpu_index'), + pciBusId: Row::string($row, 'pci_bus_id'), + name: Row::string($row, 'name'), + driverVersion: Row::string($row, 'driver_version'), + tool: Row::string($row, 'tool'), + toolVersion: Row::string($row, 'tool_version'), + presence: Presence::tryFrom(Row::string($row, 'presence')) ?? Presence::Present, + missingCount: Row::int($row, 'missing_count', 0, 0), + replacesGpuId: Row::int($row, 'replaces_gpu_id', 0, 0), + pendingNodeId: Row::int($row, 'pending_node_id', 0, 0), + pendingSince: Row::int($row, 'pending_since', 0, 0), + firstSeen: Row::int($row, 'first_seen', 0, 0), + lastSeen: Row::int($row, 'last_seen', 0, 0), + ); + } + + /** + * Column values for every field except the id. + * + * @return array + */ + public function toRow(): array { + return [ + 'vendor' => $this->vendor->value, + 'uuid' => $this->uuid, + 'node_id' => $this->nodeId, + 'gpu_index' => $this->index, + 'pci_bus_id' => $this->pciBusId, + 'name' => $this->name, + 'driver_version' => $this->driverVersion, + 'tool' => $this->tool, + 'tool_version' => $this->toolVersion, + 'presence' => $this->presence->value, + 'missing_count' => $this->missingCount, + 'replaces_gpu_id' => $this->replacesGpuId, + 'pending_node_id' => $this->pendingNodeId, + 'pending_since' => $this->pendingSince, + 'first_seen' => $this->firstSeen, + 'last_seen' => $this->lastSeen, + ]; + } + + public function key(): string { + return $this->vendor->value . '/' . $this->uuid; + } + + /** + * A UUID no record holds: a new GPU with its own history. $replacesGpuId + * names the record it may have replaced, but nothing is inherited from it. + */ + public static function discovered(GpuReport $report, GpuSnapshot $snapshot, int $nodeId, int $replacesGpuId, int $now): self { + return new self(0, $report->vendor, $report->uuid, $nodeId, $report->index, $report->pciBusId, $report->name, $report->driverVersion, $snapshot->tool, $snapshot->toolVersion, Presence::Present, 0, $replacesGpuId, 0, 0, $now, $now); + } + + /** + * Reported at its own node: attributes take the reported values, and a + * pending move elsewhere is dropped because the GPU is back home. + */ + public function seen(GpuReport $report, GpuSnapshot $snapshot, int $now): self { + return new self($this->id, $this->vendor, $this->uuid, $this->nodeId, $report->index, $report->pciBusId, $report->name, $report->driverVersion, $snapshot->tool, $snapshot->toolVersion, Presence::Present, 0, $this->replacesGpuId, 0, 0, $this->firstSeen, $now); + } + + /** + * Reported at a different node. The record stays with its node until an + * operator confirms the move (REQ-ID-004); only the pending node changes. + */ + public function seenElsewhere(int $nodeId, int $now): self { + $since = $this->pendingNodeId === $nodeId ? $this->pendingSince : $now; + + return new self($this->id, $this->vendor, $this->uuid, $this->nodeId, $this->index, $this->pciBusId, $this->name, $this->driverVersion, $this->tool, $this->toolVersion, $this->presence, $this->missingCount, $this->replacesGpuId, $nodeId, $since, $this->firstSeen, $this->lastSeen); + } + + /** + * Not reported by a successful collection at its node. Absent after + * $absentAfter misses in a row; never deleted (REQ-ID-005). + */ + public function missed(int $absentAfter): self { + $missing = $this->missingCount + 1; + + return new self($this->id, $this->vendor, $this->uuid, $this->nodeId, $this->index, $this->pciBusId, $this->name, $this->driverVersion, $this->tool, $this->toolVersion, $missing >= $absentAfter ? Presence::Absent : $this->presence, $missing, $this->replacesGpuId, $this->pendingNodeId, $this->pendingSince, $this->firstSeen, $this->lastSeen); + } + + public function possibleReplacement(): bool { + return $this->replacesGpuId > 0; + } + + public function movePending(): bool { + return $this->pendingNodeId > 0; + } +} diff --git a/lib/GpuReport.php b/lib/GpuReport.php new file mode 100644 index 0000000..d667b50 --- /dev/null +++ b/lib/GpuReport.php @@ -0,0 +1,119 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * One GPU as a vendor tool reported it in one collection, validated. + * + * Tool output is untrusted (PLAN, Security), so every field is checked or + * cleaned here, before it can reach the database or a page. A report that + * fails a check is refused as a whole; the caller treats the collection as + * failed rather than guessing. + */ +final readonly class GpuReport { + // NVML prints "GPU-" and a hyphenated 128-bit UUID in hex. + private const NVIDIA_UUID = '/^GPU-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/'; + + // domain:bus:device.function, hex. nvidia-smi prints an eight-digit + // domain, DCGM and the kernel four. + private const PCI_BUS_ID = '/^([0-9a-f]{4,8}):([0-9a-f]{2}):([0-9a-f]{2})\.([0-7])$/'; + + private function __construct( + public Vendor $vendor, + public string $uuid, + public ?int $index, + public string $pciBusId, + public string $name, + public string $driverVersion, + ) { + } + + /** + * @param ?int $index null when the tool reported the index as unavailable + * + * @throws \InvalidArgumentException naming the field, never echoing its value + */ + public static function create(Vendor $vendor, string $uuid, ?int $index, string $pciBusId, string $name, string $driverVersion): self { + return new self( + vendor: $vendor, + uuid: self::uuid($vendor, $uuid), + index: $index === null || $index >= 0 ? $index : throw new \InvalidArgumentException('GPU index is negative'), + pciBusId: self::busId($pciBusId), + name: self::clean($name, 128), + driverVersion: self::clean($driverVersion, 64), + ); + } + + /** + * The identity key (REQ-ID-001). Only a whole-GPU UUID qualifies. + * + * MIG instance UUIDs are refused: NVML documents them as immutable only + * for one instance lifetime, and whether a recreated instance can get a + * UUID back is unresolved (research/mig.md). Keying on one could attach a + * destroyed instance's history to a new one, so MIG waits for decision #13. + */ + private static function uuid(Vendor $vendor, string $uuid): string { + $uuid = trim($uuid); + + if (stripos($uuid, 'MIG-') === 0) { + throw new \InvalidArgumentException('GPU UUID is a MIG instance UUID, which is not an identity key'); + } + + $key = match ($vendor) { + Vendor::Nvidia => 'GPU-' . strtolower(substr($uuid, 4)), + }; + + if (strncmp($uuid, 'GPU-', 4) !== 0 || preg_match(self::NVIDIA_UUID, $key) !== 1) { + throw new \InvalidArgumentException('GPU UUID is not in the vendor format'); + } + + return $key; + } + + /** + * Normalized to nvidia-smi's spelling, an eight-digit domain in upper + * case, so the same slot compares equal whichever tool reported it. + */ + private static function busId(string $busId): string { + if (preg_match(self::PCI_BUS_ID, strtolower(trim($busId)), $parts) !== 1) { + throw new \InvalidArgumentException('PCI bus ID is not domain:bus:device.function'); + } + + return strtoupper(sprintf('%08s:%s:%s.%s', $parts[1], $parts[2], $parts[3], $parts[4])); + } + + /** + * Free text from a tool: control characters removed, whitespace trimmed, + * and cut to the column width. Escaping happens where it is printed. + */ + public static function clean(string $text, int $length): string { + $text = (string) preg_replace('/[\x00-\x1F\x7F]+/', ' ', $text); + + if (!mb_check_encoding($text, 'UTF-8')) { + $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8'); + } + + return mb_substr(trim($text), 0, $length); + } + + public function key(): string { + return $this->vendor->value . '/' . $this->uuid; + } +} diff --git a/lib/GpuRepository.php b/lib/GpuRepository.php new file mode 100644 index 0000000..27effe8 --- /dev/null +++ b/lib/GpuRepository.php @@ -0,0 +1,120 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * GPU identity records. The unique key on (vendor, uuid) is the last line of + * defence for REQ-ID-001: a second record for one UUID fails to insert even + * if two writers race. + */ +final class GpuRepository { + public function __construct(private readonly \PDO|false $connection) { + } + + /** + * The records IdentityReconciler needs for one snapshot: everything at the + * node, and any record elsewhere that the snapshot reports. + * + * @return list + */ + public function forReconcile(Node $node, GpuSnapshot $snapshot): array { + $uuids = $snapshot->uuids(); + $sql = 'SELECT * FROM plugin_gpu_gpu WHERE node_id = ?'; + + if ($uuids !== []) { + $sql .= ' OR uuid IN (' . implode(', ', array_fill(0, count($uuids), '?')) . ')'; + } + + return $this->records(db_fetch_assoc_prepared($sql . ' ORDER BY id', array_merge([$node->id], $uuids), true, $this->connection)); + } + + /** + * @return list + */ + public function all(): array { + return $this->records(db_fetch_assoc_prepared('SELECT * FROM plugin_gpu_gpu ORDER BY node_id, gpu_index, uuid', [], true, $this->connection)); + } + + /** + * @return list + */ + public function pendingMoves(): array { + return $this->records(db_fetch_assoc_prepared('SELECT * FROM plugin_gpu_gpu WHERE pending_node_id > 0 ORDER BY pending_since, id', [], true, $this->connection)); + } + + /** + * Write a reconciliation. Each statement stands alone and the next + * collection recomputes from what was stored, so a run stopped part way + * leaves records that the next run completes rather than corrupts. + */ + public function apply(Reconciliation $changes): bool { + $ok = true; + + foreach ($changes->created as $record) { + $row = $record->toRow(); + $ok = db_execute_prepared('INSERT INTO plugin_gpu_gpu (' . implode(', ', array_keys($row)) . ') VALUES (' . implode(', ', array_fill(0, count($row), '?')) . ')', array_values($row), true, $this->connection) && $ok; + } + + foreach ($changes->updated as $record) { + $row = $record->toRow(); + + // Vendor and UUID are the key; an update never rewrites them. + unset($row['vendor'], $row['uuid']); + + $set = implode(', ', array_map(static fn (string $column): string => "$column = ?", array_keys($row))); + $ok = db_execute_prepared("UPDATE plugin_gpu_gpu SET $set WHERE id = ?", array_merge(array_values($row), [$record->id]), true, $this->connection) && $ok; + } + + return $ok; + } + + /** + * The operator's confirmation of a pending move (REQ-ID-004). The GPU + * keeps its record, and so its history; only its node changes. + */ + public function confirmMove(int $id): bool { + $ok = db_execute_prepared("UPDATE plugin_gpu_gpu SET node_id = pending_node_id, pending_node_id = 0, pending_since = 0, missing_count = 0, presence = 'present' WHERE id = ? AND pending_node_id > 0", [$id], true, $this->connection); + + return $ok && db_affected_rows($this->connection) === 1; + } + + public function rejectMove(int $id): bool { + $ok = db_execute_prepared('UPDATE plugin_gpu_gpu SET pending_node_id = 0, pending_since = 0 WHERE id = ? AND pending_node_id > 0', [$id], true, $this->connection); + + return $ok && db_affected_rows($this->connection) === 1; + } + + /** + * @return list + */ + private function records(mixed $rows): array { + $records = []; + + foreach (Row::rows($rows) as $row) { + $record = GpuRecord::fromRow($row); + + if ($record !== null) { + $records[] = $record; + } + } + + return $records; + } +} diff --git a/lib/GpuSnapshot.php b/lib/GpuSnapshot.php new file mode 100644 index 0000000..7623777 --- /dev/null +++ b/lib/GpuSnapshot.php @@ -0,0 +1,80 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Everything one successful collection at one node reported. A failed + * collection produces no snapshot, so it can never mark a GPU absent. + */ +final readonly class GpuSnapshot { + /** + * @param list $reports + */ + private function __construct( + public string $tool, + public string $toolVersion, + public array $reports, + ) { + } + + /** + * @param list $reports + * + * @throws \InvalidArgumentException when two reports share a UUID or a bus + * ID, which no real node produces; the + * output was misread and is refused + */ + public static function create(string $tool, string $toolVersion, array $reports): self { + $keys = []; + $buses = []; + + foreach ($reports as $report) { + if (isset($keys[$report->key()])) { + throw new \InvalidArgumentException('Two GPUs in one collection report the same UUID'); + } + + if (isset($buses[$report->pciBusId])) { + throw new \InvalidArgumentException('Two GPUs in one collection report the same PCI bus ID'); + } + + $keys[$report->key()] = true; + $buses[$report->pciBusId] = true; + } + + return new self(GpuReport::clean($tool, 32), GpuReport::clean($toolVersion, 64), $reports); + } + + public function has(string $key): bool { + foreach ($this->reports as $report) { + if ($report->key() === $key) { + return true; + } + } + + return false; + } + + /** + * @return list + */ + public function uuids(): array { + return array_map(static fn (GpuReport $report): string => $report->uuid, $this->reports); + } +} diff --git a/lib/IdentityReconciler.php b/lib/IdentityReconciler.php new file mode 100644 index 0000000..63b7672 --- /dev/null +++ b/lib/IdentityReconciler.php @@ -0,0 +1,107 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Decides how one node's snapshot changes the GPU records (PLAN, GPU + * identity; REQ-ID-001 to REQ-ID-005). It only decides; it reads and writes + * nothing, so every identity rule is tested without a database. + * + * The rules, in the order they apply: + * + * - A disabled node, or a snapshot with no GPUs, changes nothing. A tool that + * suddenly reports nothing is far likelier broken than every card gone. + * - A reported UUID with a record at this node updates that record in place. + * - A reported UUID with a record at another node leaves the record where it + * is and marks the move pending until an operator confirms it. + * - A reported UUID with no record creates one. If an earlier record at this + * node sat on the same PCI bus ID and was not reported now, the new record + * is flagged as its possible replacement and inherits nothing. The rule + * matches on the bus ID alone, not also the index, because the index can + * change at every boot and a replacement must not escape the flag that way. + * - A record at this node that was not reported counts a miss, and is marked + * absent at the configured count. It is never deleted. + */ +final class IdentityReconciler { + /** + * @param list $known every record at this node, plus any record + * elsewhere whose UUID the snapshot reports + */ + public function reconcile(Node $node, array $known, GpuSnapshot $snapshot, int $absentAfter, int $now): Reconciliation { + if (!$node->enabled() || $snapshot->reports === []) { + return new Reconciliation(); + } + + $byKey = []; + + foreach ($known as $record) { + $byKey[$record->key()] = $record; + } + + $created = []; + $updated = []; + + foreach ($snapshot->reports as $report) { + $record = $byKey[$report->key()] ?? null; + + if ($record === null) { + $created[] = GpuRecord::discovered($report, $snapshot, $node->id, $this->replaced($node, $known, $snapshot, $report), $now); + } elseif ($record->nodeId === $node->id) { + $updated[] = $record->seen($report, $snapshot, $now); + } else { + $moved = $record->seenElsewhere($node->id, $now); + + if ($moved != $record) { + $updated[] = $moved; + } + } + } + + foreach ($known as $record) { + if ($record->nodeId === $node->id && !$snapshot->has($record->key()) && $record->presence !== Presence::Absent) { + $updated[] = $record->missed($absentAfter); + } + } + + return new Reconciliation($created, $updated); + } + + /** + * The id of the record a new GPU may have replaced, or 0. When several + * earlier cards sat on that bus ID, the one seen last is named. + * + * @param list $known + */ + private function replaced(Node $node, array $known, GpuSnapshot $snapshot, GpuReport $report): int { + $candidate = null; + + foreach ($known as $record) { + if ($record->nodeId !== $node->id || $record->vendor !== $report->vendor || $record->pciBusId !== $report->pciBusId || $snapshot->has($record->key())) { + continue; + } + + if ($candidate === null || [$record->lastSeen, $record->id] > [$candidate->lastSeen, $candidate->id]) { + $candidate = $record; + } + } + + return $candidate->id ?? 0; + } +} diff --git a/lib/Inventory.php b/lib/Inventory.php new file mode 100644 index 0000000..ba0d85a --- /dev/null +++ b/lib/Inventory.php @@ -0,0 +1,57 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Records one node's snapshot: reads the records the snapshot touches, + * reconciles, and writes the result. The collector (milestone 3) calls this + * once per successful collection and never for a failed one. + */ +final class Inventory { + public function __construct( + private readonly GpuRepository $gpus, + private readonly IdentityReconciler $reconciler, + private readonly Clock $clock, + ) { + } + + public function record(Node $node, GpuSnapshot $snapshot, int $absentAfter): Reconciliation { + $changes = $this->reconciler->reconcile($node, $this->gpus->forReconcile($node, $snapshot), $snapshot, $absentAfter, $this->clock->now()); + + if ($changes->isEmpty()) { + return $changes; + } + + if (!$this->gpus->apply($changes)) { + Log::warning(sprintf('Not every GPU record change for node %d was stored; the next collection retries', $node->id)); + } + + $summary = sprintf('Node %d: %d new GPU records, %d updated', $node->id, count($changes->created), count($changes->updated)); + + // A new identity is worth a note; routine updates are debug detail. + if ($changes->created === []) { + Log::debug($summary); + } else { + Log::info($summary); + } + + return $changes; + } +} diff --git a/lib/InventoryExport.php b/lib/InventoryExport.php new file mode 100644 index 0000000..e7322a8 --- /dev/null +++ b/lib/InventoryExport.php @@ -0,0 +1,50 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * The export an administrator takes before an uninstall that drops the + * plugin tables (REQ-LIFE-004): every node and GPU record, as JSON. It holds + * UUIDs and device descriptions, so only GPU Admin can download it. + */ +final class InventoryExport { + /** + * @param list $nodes + * @param list $gpus + */ + public static function json(array $nodes, array $gpus, string $pluginVersion, int $now): string { + $document = [ + 'plugin' => 'gpu', + 'version' => $pluginVersion, + 'exported_at' => gmdate('Y-m-d\TH:i:s\Z', $now), + 'nodes' => array_map(static fn (Node $node): array => [ + 'id' => $node->id, + 'host_id' => $node->hostId, + 'description' => $node->description, + 'admin_state' => $node->adminState->value, + 'created_at' => $node->createdAt, + 'updated_at' => $node->updatedAt, + ], $nodes), + 'gpus' => array_map(static fn (GpuRecord $gpu): array => ['id' => $gpu->id] + $gpu->toRow(), $gpus), + ]; + + return json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR) . "\n"; + } +} diff --git a/lib/Node.php b/lib/Node.php new file mode 100644 index 0000000..82eb8cf --- /dev/null +++ b/lib/Node.php @@ -0,0 +1,59 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * A Cacti device registered as a GPU node. The device itself stays Cacti's; + * the plugin only refers to it by id. + */ +final readonly class Node { + public function __construct( + public int $id, + public int $hostId, + public AdminState $adminState, + public string $description, + // False once the Cacti device has been deleted; the node row stays + // so its GPU records keep their owner. + public bool $deviceExists, + public int $createdAt, + public int $updatedAt, + ) { + } + + /** + * @param array $row a plugin_gpu_node row, left joined to host as + * description and device_id + */ + public static function fromRow(array $row): self { + return new self( + id: Row::int($row, 'id'), + hostId: Row::int($row, 'host_id'), + adminState: AdminState::tryFrom(Row::string($row, 'admin_state')) ?? AdminState::Disabled, + description: Row::string($row, 'description'), + deviceExists: Row::int($row, 'device_id') > 0, + createdAt: Row::int($row, 'created_at'), + updatedAt: Row::int($row, 'updated_at'), + ); + } + + public function enabled(): bool { + return $this->adminState === AdminState::Enabled; + } +} diff --git a/lib/NodeRepository.php b/lib/NodeRepository.php new file mode 100644 index 0000000..827a56e --- /dev/null +++ b/lib/NodeRepository.php @@ -0,0 +1,104 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Registered GPU nodes. Reads Cacti's host table for descriptions and never + * writes it: registering, disabling, or removing a node leaves the Cacti + * device as it was (REQ-LIFE-003). + */ +final class NodeRepository { + private const SELECT = 'SELECT n.*, h.id AS device_id, h.description FROM plugin_gpu_node AS n LEFT JOIN host AS h ON h.id = n.host_id'; + + public function __construct(private readonly \PDO|false $connection, private readonly Clock $clock) { + } + + public function find(int $id): ?Node { + $row = db_fetch_row_prepared(self::SELECT . ' WHERE n.id = ?', [$id], true, $this->connection); + + return is_array($row) && $row !== [] ? Node::fromRow($row) : null; + } + + /** + * @return list + */ + public function all(): array { + return array_map(Node::fromRow(...), Row::rows(db_fetch_assoc_prepared(self::SELECT . ' ORDER BY h.description, n.id', [], true, $this->connection))); + } + + /** + * Cacti devices an operator can register: those not registered yet, plus + * the node's own device when one is being edited. + * + * @return array host id => description + */ + public function devicesFor(int $nodeId): array { + $devices = []; + + foreach (Row::rows(db_fetch_assoc_prepared('SELECT h.id, h.description FROM host AS h LEFT JOIN plugin_gpu_node AS n ON n.host_id = h.id WHERE n.id IS NULL OR n.id = ? ORDER BY h.description', [$nodeId], true, $this->connection)) as $row) { + $devices[Row::int($row, 'id')] = Row::string($row, 'description'); + } + + return $devices; + } + + public function deviceExists(int $hostId): bool { + return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM host WHERE id = ?', [$hostId], '', true, $this->connection) === 1; + } + + public function hostTaken(int $hostId, int $exceptId): bool { + return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_gpu_node WHERE host_id = ? AND id != ?', [$hostId, $exceptId], '', true, $this->connection) > 0; + } + + /** + * Insert ($id 0) or update a node, returning its id, or 0 when nothing + * was written. + */ + public function save(int $id, int $hostId, AdminState $state): int { + $now = $this->clock->now(); + + if ($id === 0) { + $ok = db_execute_prepared('INSERT INTO plugin_gpu_node (host_id, admin_state, created_at, updated_at) VALUES (?, ?, ?, ?)', [$hostId, $state->value, $now, $now], true, $this->connection); + + return $ok ? (int) db_fetch_insert_id($this->connection) : 0; + } + + if ($this->find($id) === null) { + return 0; + } + + $ok = db_execute_prepared('UPDATE plugin_gpu_node SET host_id = ?, admin_state = ?, updated_at = ? WHERE id = ?', [$hostId, $state->value, $now, $id], true, $this->connection); + + return $ok ? $id : 0; + } + + /** + * Remove a node that owns no GPU records. A node with records keeps them + * and can only be disabled, because GPU records are never deleted for + * the operator by accident (REQ-ID-005). + */ + public function delete(int $id): bool { + // One statement, so a GPU recorded between a check and the delete + // cannot be orphaned. + $ok = db_execute_prepared('DELETE FROM plugin_gpu_node WHERE id = ? AND NOT EXISTS (SELECT 1 FROM plugin_gpu_gpu WHERE node_id = ? OR pending_node_id = ?)', [$id, $id, $id], true, $this->connection); + + return $ok && db_affected_rows($this->connection) === 1; + } +} diff --git a/lib/Presence.php b/lib/Presence.php new file mode 100644 index 0000000..6605dd0 --- /dev/null +++ b/lib/Presence.php @@ -0,0 +1,30 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * Whether the latest successful collections at a GPU's node reported it. A + * possible replacement is recorded separately (GpuRecord::$replacesGpuId), + * because a replacement card is itself present. + */ +enum Presence: string { + case Present = 'present'; + case Absent = 'absent'; +} diff --git a/lib/Reconciliation.php b/lib/Reconciliation.php new file mode 100644 index 0000000..f01717a --- /dev/null +++ b/lib/Reconciliation.php @@ -0,0 +1,40 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * The record changes one snapshot calls for. GpuRepository::apply() writes + * them; nothing else does. + */ +final readonly class Reconciliation { + /** + * @param list $created new identities, with id 0 + * @param list $updated existing records in their new state + */ + public function __construct( + public array $created = [], + public array $updated = [], + ) { + } + + public function isEmpty(): bool { + return $this->created === [] && $this->updated === []; + } +} diff --git a/lib/Vendor.php b/lib/Vendor.php new file mode 100644 index 0000000..155c9c5 --- /dev/null +++ b/lib/Vendor.php @@ -0,0 +1,35 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * GPU vendors whose identity rule is settled. ADR 0003 is accepted for NVIDIA + * only; AMD joins when research #19 shows its UUIDs are stable, so no AMD + * record can be created before then. + */ +enum Vendor: string { + case Nvidia = 'nvidia'; + + public function label(): string { + return match ($this) { + self::Nvidia => 'NVIDIA', + }; + } +} diff --git a/tests/Unit/GpuReportTest.php b/tests/Unit/GpuReportTest.php new file mode 100644 index 0000000..78dd847 --- /dev/null +++ b/tests/Unit/GpuReportTest.php @@ -0,0 +1,95 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Gpu\GpuReport; +use Somethingwithproof\Gpu\GpuSnapshot; +use Somethingwithproof\Gpu\Vendor; + +const GPU_A = 'GPU-00000000-0000-4000-8000-0000000000a1'; +const GPU_B = 'GPU-00000000-0000-4000-8000-0000000000b2'; + +function gpu_report(string $uuid = GPU_A, ?int $index = 0, string $bus = '00000000:3B:00.0', string $name = 'NVIDIA Test GPU', string $driver = '580.95.05'): GpuReport { + return GpuReport::create(Vendor::Nvidia, $uuid, $index, $bus, $name, $driver); +} + +it('keys a GPU by vendor and lower-case UUID', function () { + $report = gpu_report(' GPU-00000000-0000-4000-8000-0000000000A1 '); + + expect($report->uuid)->toBe(GPU_A) + ->and($report->key())->toBe('nvidia/' . GPU_A); +}); + +it('refuses MIG instance UUIDs as identity keys, in both spellings', function (string $uuid) { + expect(fn () => gpu_report($uuid))->toThrow(InvalidArgumentException::class, 'MIG instance UUID'); +})->with([ + 'MIG-00000000-0000-4000-8000-0000000000c3', + 'MIG-GPU-00000000-0000-4000-8000-0000000000a1/1/0', + 'mig-00000000-0000-4000-8000-0000000000c3', +]); + +it('refuses a UUID that is not in the vendor format', function (string $uuid) { + expect(fn () => gpu_report($uuid))->toThrow(InvalidArgumentException::class, 'vendor format'); +})->with([ + '', + '[N/A]', + '00000000-0000-4000-8000-0000000000a1', + 'gpu-00000000-0000-4000-8000-0000000000a1', + 'GPU-00000000-0000-4000-8000-0000000000a1; rm -rf /', + 'GPU-00000000-0000-4000-8000-0000000000a', +]); + +it('normalizes the PCI bus ID to an eight-digit upper-case domain', function (string $bus) { + expect(gpu_report(bus: $bus)->pciBusId)->toBe('00000000:3B:00.0'); +})->with(['00000000:3B:00.0', '0000:3b:00.0', ' 00000000:3b:00.0 ']); + +it('refuses a malformed PCI bus ID', function (string $bus) { + expect(fn () => gpu_report(bus: $bus))->toThrow(InvalidArgumentException::class, 'PCI bus ID'); +})->with(['', '[N/A]', '3B:00.0', '00000000:3B:00.8', '00000000:3B:00']); + +it('keeps an unavailable index as unknown and refuses a negative one', function () { + expect(gpu_report(index: null)->index)->toBeNull() + ->and(fn () => gpu_report(index: -1))->toThrow(InvalidArgumentException::class, 'negative'); +}); + +it('strips control characters from tool text and cuts it to the column width', function () { + $report = gpu_report(name: "NVIDIA\x1b[31m Test\nGPU\x00" . str_repeat('x', 200), driver: "580.95.05\r\n"); + + expect($report->name)->not->toMatch('/[\x00-\x1F\x7F]/') + ->and(mb_strlen($report->name))->toBe(128) + ->and($report->name)->toStartWith('NVIDIA [31m Test GPU') + ->and($report->driverVersion)->toBe('580.95.05'); +}); + +it('keeps markup in names as text, for the page to escape', function () { + expect(gpu_report(name: '')->name)->toBe(''); +}); + +it('refuses a snapshot that reports one UUID or one bus ID twice', function () { + expect(fn () => GpuSnapshot::create('nvidia-smi', '580.95.05', [gpu_report(), gpu_report(bus: '00000000:3C:00.0')]))->toThrow(InvalidArgumentException::class, 'same UUID') + ->and(fn () => GpuSnapshot::create('nvidia-smi', '580.95.05', [gpu_report(), gpu_report(GPU_B)]))->toThrow(InvalidArgumentException::class, 'same PCI bus ID'); +}); + +it('accepts distinct GPUs and records the tool that reported them', function () { + $snapshot = GpuSnapshot::create("nvidia-smi\n", '580.95.05', [gpu_report(), gpu_report(GPU_B, 1, '00000000:3C:00.0')]); + + expect($snapshot->tool)->toBe('nvidia-smi') + ->and($snapshot->uuids())->toBe([GPU_A, GPU_B]) + ->and($snapshot->has('nvidia/' . GPU_B))->toBeTrue() + ->and($snapshot->has('nvidia/GPU-00000000-0000-4000-8000-0000000000ff'))->toBeFalse(); +}); diff --git a/tests/Unit/IdentityTest.php b/tests/Unit/IdentityTest.php new file mode 100644 index 0000000..4a3c5ea --- /dev/null +++ b/tests/Unit/IdentityTest.php @@ -0,0 +1,182 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Identity rules (REQ-ID-001 to REQ-ID-005) driven by the sequences in + * tests/fixtures/identity/. Each sequence is replayed against an in-memory + * store that behaves as GpuRepository does: ids in insert order, updates by + * id, and an operator's move confirmation as confirmMove() writes it. + */ + +use Somethingwithproof\Gpu\AdminState; +use Somethingwithproof\Gpu\GpuRecord; +use Somethingwithproof\Gpu\GpuReport; +use Somethingwithproof\Gpu\GpuSnapshot; +use Somethingwithproof\Gpu\IdentityReconciler; +use Somethingwithproof\Gpu\Node; +use Somethingwithproof\Gpu\Presence; +use Somethingwithproof\Gpu\Vendor; + +/** + * @return array}> + */ +function identity_fixtures(): array { + $fixtures = []; + + foreach (glob(dirname(__DIR__) . '/fixtures/identity/*.json') as $file) { + $fixtures[basename($file, '.json')] = [json_decode((string) file_get_contents($file), true, 512, JSON_THROW_ON_ERROR)]; + } + + return $fixtures; +} + +/** + * @param array $fixture + * @return array{records: array, refused: int} + */ +function identity_replay(array $fixture): array { + $reconciler = new IdentityReconciler(); + $records = []; + $refused = 0; + $nextId = 1; + + foreach ($fixture['steps'] as $step) { + if (isset($step['confirm_move'])) { + foreach ($records as $id => $record) { + if ($record->uuid === $step['confirm_move'] && $record->pendingNodeId > 0) { + $records[$id] = new GpuRecord($record->id, $record->vendor, $record->uuid, $record->pendingNodeId, $record->index, $record->pciBusId, $record->name, $record->driverVersion, $record->tool, $record->toolVersion, Presence::Present, 0, $record->replacesGpuId, 0, 0, $record->firstSeen, $record->lastSeen); + } + } + + continue; + } + + // A failed collection produces no snapshot at all. + if (!empty($step['failed'])) { + continue; + } + + try { + $snapshot = GpuSnapshot::create($step['tool'], $step['tool_version'], array_map( + static fn (array $gpu): GpuReport => GpuReport::create(Vendor::Nvidia, $gpu['uuid'], $gpu['index'], $gpu['bus'], $gpu['name'], $gpu['driver']), + $step['gpus'] + )); + } catch (InvalidArgumentException) { + $refused++; + + continue; + } + + $state = $fixture['nodes'][(string) $step['node']] === 'enabled' ? AdminState::Enabled : AdminState::Disabled; + $node = new Node($step['node'], 100 + $step['node'], $state, 'node' . $step['node'], true, 0, 0); + $known = array_values(array_filter($records, static fn (GpuRecord $r): bool => $r->nodeId === $node->id || $snapshot->has($r->key()))); + + $changes = $reconciler->reconcile($node, $known, $snapshot, $fixture['absent_after'], $step['at']); + + foreach ($changes->created as $record) { + $id = $nextId++; + $records[$id] = new GpuRecord($id, $record->vendor, $record->uuid, $record->nodeId, $record->index, $record->pciBusId, $record->name, $record->driverVersion, $record->tool, $record->toolVersion, $record->presence, $record->missingCount, $record->replacesGpuId, $record->pendingNodeId, $record->pendingSince, $record->firstSeen, $record->lastSeen); + } + + foreach ($changes->updated as $record) { + expect($records)->toHaveKey($record->id); + + $records[$record->id] = $record; + } + } + + return ['records' => $records, 'refused' => $refused]; +} + +it('produces the documented records', function (array $fixture) { + $result = identity_replay($fixture); + $records = $result['records']; + $uuids = []; + + foreach ($records as $record) { + $uuids[$record->id] = $record->uuid; + } + + expect(count($records))->toBe(count($fixture['expect'])) + ->and($result['refused'])->toBe($fixture['refused'] ?? 0); + + foreach ($fixture['expect'] as $expected) { + $matches = array_values(array_filter($records, static fn (GpuRecord $r): bool => $r->uuid === $expected['uuid'])); + + expect($matches)->toHaveCount(1, $expected['uuid']); + + $record = $matches[0]; + $actual = [ + 'uuid' => $record->uuid, + 'node' => $record->nodeId, + 'index' => $record->index, + 'bus' => $record->pciBusId, + 'driver' => $record->driverVersion, + 'tool' => $record->tool, + 'tool_version' => $record->toolVersion, + 'presence' => $record->presence->value, + 'missing' => $record->missingCount, + 'replaces' => $record->replacesGpuId > 0 ? $uuids[$record->replacesGpuId] : null, + 'pending_node' => $record->pendingNodeId, + 'pending_since' => $record->pendingSince, + 'first_seen' => $record->firstSeen, + 'last_seen' => $record->lastSeen, + ]; + + $actual = array_intersect_key($actual, $expected); + + ksort($actual); + ksort($expected); + + expect($actual)->toBe($expected); + } +})->with(identity_fixtures()); + +it('never produces two records for one UUID', function (array $fixture) { + $keys = array_map(static fn (GpuRecord $r): string => $r->key(), identity_replay($fixture)['records']); + + expect($keys)->toBe(array_unique($keys)); +})->with(identity_fixtures()); + +it('covers every identity scenario the plan names', function () { + expect(array_keys(identity_fixtures()))->toContain('reboot-reorder', 'card-swap', 'slot-move', 'driver-change', 'lost-gpu', 'node-move-pending', 'node-move-confirmed', 'unavailable-values', 'refused-output'); +}); + +it('uses only synthetic UUIDs in fixtures', function (array $fixture) { + // REQ-TEST-005: no UUID of real hardware. Every UUID in a fixture uses + // the reserved all-zero prefix. + preg_match_all('/(?:GPU|MIG)-[0-9a-fA-F-]{8,}/', (string) json_encode($fixture), $found); + + expect($found[0])->not->toBeEmpty(); + + foreach ($found[0] as $uuid) { + expect($uuid)->toMatch('/^(GPU|MIG)-00000000-0000-4000-8000-0000000000[0-9a-f]{2}$/'); + } + + expect($fixture['source'])->toStartWith('synthetic'); +})->with(identity_fixtures()); + +it('changes nothing for a disabled node or an empty snapshot', function () { + $reconciler = new IdentityReconciler(); + $snapshot = GpuSnapshot::create('nvidia-smi', '580.95.05', [GpuReport::create(Vendor::Nvidia, 'GPU-00000000-0000-4000-8000-0000000000a1', 0, '00000000:3B:00.0', 'GPU', '580.95.05')]); + $known = [GpuRecord::discovered($snapshot->reports[0], $snapshot, 1, 0, 10)]; + + expect($reconciler->reconcile(new Node(1, 101, AdminState::Disabled, 'n', true, 0, 0), $known, $snapshot, 1, 20)->isEmpty())->toBeTrue() + ->and($reconciler->reconcile(new Node(1, 101, AdminState::Enabled, 'n', true, 0, 0), $known, GpuSnapshot::create('nvidia-smi', '580.95.05', []), 1, 20)->isEmpty())->toBeTrue(); +}); diff --git a/tests/Unit/RepositoryTest.php b/tests/Unit/RepositoryTest.php new file mode 100644 index 0000000..5e1039a --- /dev/null +++ b/tests/Unit/RepositoryTest.php @@ -0,0 +1,142 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Gpu\AdminState; +use Somethingwithproof\Gpu\FixedClock; +use Somethingwithproof\Gpu\GpuRecord; +use Somethingwithproof\Gpu\GpuReport; +use Somethingwithproof\Gpu\GpuRepository; +use Somethingwithproof\Gpu\GpuSnapshot; +use Somethingwithproof\Gpu\IdentityReconciler; +use Somethingwithproof\Gpu\Inventory; +use Somethingwithproof\Gpu\InventoryExport; +use Somethingwithproof\Gpu\Node; +use Somethingwithproof\Gpu\NodeRepository; +use Somethingwithproof\Gpu\Presence; +use Somethingwithproof\Gpu\Vendor; + +beforeEach(function () { + $GLOBALS['__gpu_db_exec'] = []; + $GLOBALS['__gpu_db_rows'] = []; + $GLOBALS['__gpu_log'] = []; + $GLOBALS['__gpu_affected_rows'] = 1; +}); + +function repo_snapshot(string ...$uuids): GpuSnapshot { + $reports = []; + + foreach (array_values($uuids) as $i => $uuid) { + $reports[] = GpuReport::create(Vendor::Nvidia, $uuid, $i, sprintf('00000000:%02X:00.0', 0x3B + $i), 'NVIDIA Test GPU', '580.95.05'); + } + + return GpuSnapshot::create('nvidia-smi', '580.95.05', $reports); +} + +function repo_node(int $id = 1, AdminState $state = AdminState::Enabled): Node { + return new Node($id, 100 + $id, $state, 'node' . $id, true, 0, 0); +} + +it('inserts new records with every column and updates others without touching the key', function () { + $snapshot = repo_snapshot('GPU-00000000-0000-4000-8000-0000000000a1'); + $created = GpuRecord::discovered($snapshot->reports[0], $snapshot, 1, 0, 50); + $updated = new GpuRecord(7, Vendor::Nvidia, 'GPU-00000000-0000-4000-8000-0000000000b2', 1, null, '00000000:3C:00.0', 'n', 'd', 't', 'v', Presence::Absent, 3, 0, 0, 0, 10, 20); + + expect((new GpuRepository(false))->apply(new \Somethingwithproof\Gpu\Reconciliation([$created], [$updated])))->toBeTrue(); + + [$insert, $update] = $GLOBALS['__gpu_db_exec']; + + expect($insert['sql'])->toStartWith('INSERT INTO plugin_gpu_gpu (vendor, uuid, node_id, gpu_index,') + ->and($insert['params'])->toBe(array_values($created->toRow())) + ->and($update['sql'])->toStartWith('UPDATE plugin_gpu_gpu SET node_id = ?') + ->and($update['sql'])->not->toContain('uuid') + ->and($update['sql'])->not->toContain('vendor') + ->and($update['sql'])->toEndWith('WHERE id = ?') + ->and($update['params'][1])->toBeNull() + ->and(end($update['params']))->toBe(7); +}); + +it('reads stored records back, skipping rows of a vendor this code does not know', function () { + $GLOBALS['__gpu_db_rows']['FROM plugin_gpu_gpu'] = [ + ['id' => '3', 'vendor' => 'nvidia', 'uuid' => 'GPU-00000000-0000-4000-8000-0000000000a1', 'node_id' => '4', 'gpu_index' => null, 'pci_bus_id' => '00000000:3B:00.0', 'presence' => 'absent', 'missing_count' => '2', 'replaces_gpu_id' => '0', 'pending_node_id' => '0', 'pending_since' => '0', 'first_seen' => '10', 'last_seen' => '20'], + ['id' => '4', 'vendor' => 'future', 'uuid' => 'X', 'node_id' => '4'], + ]; + + $records = (new GpuRepository(false))->forReconcile(repo_node(4), repo_snapshot('GPU-00000000-0000-4000-8000-0000000000a1')); + + expect($records)->toHaveCount(1) + ->and($records[0]->id)->toBe(3) + ->and($records[0]->index)->toBeNull() + ->and($records[0]->presence)->toBe(Presence::Absent) + ->and($records[0]->missingCount)->toBe(2); +}); + +it('confirms or rejects only a pending move, and reports whether one changed', function () { + $gpus = new GpuRepository(false); + + expect($gpus->confirmMove(5))->toBeTrue() + ->and($GLOBALS['__gpu_db_exec'][0]['sql'])->toContain('SET node_id = pending_node_id') + ->and($GLOBALS['__gpu_db_exec'][0]['sql'])->toContain('AND pending_node_id > 0'); + + $GLOBALS['__gpu_affected_rows'] = 0; + + expect($gpus->confirmMove(5))->toBeFalse() + ->and($gpus->rejectMove(5))->toBeFalse(); +}); + +it('deletes a node only in the statement that checks it owns no GPU', function () { + $nodes = new NodeRepository(false, new FixedClock(100)); + + expect($nodes->delete(3))->toBeTrue() + ->and($GLOBALS['__gpu_db_exec'][0]['sql'])->toContain('NOT EXISTS (SELECT 1 FROM plugin_gpu_gpu WHERE node_id = ? OR pending_node_id = ?)') + ->and($GLOBALS['__gpu_db_exec'][0]['params'])->toBe([3, 3, 3]); + + $GLOBALS['__gpu_affected_rows'] = 0; + + expect($nodes->delete(3))->toBeFalse(); +}); + +it('records a snapshot through the repository and logs new identities by node id only', function () { + $inventory = new Inventory(new GpuRepository(false), new IdentityReconciler(), new FixedClock(500)); + $changes = $inventory->record(repo_node(2), repo_snapshot('GPU-00000000-0000-4000-8000-0000000000a1'), 3); + + expect($changes->created)->toHaveCount(1) + ->and($changes->created[0]->firstSeen)->toBe(500) + ->and($GLOBALS['__gpu_db_exec'])->toHaveCount(1) + ->and($GLOBALS['__gpu_log'])->toBe([['message' => 'NOTE: Node 2: 1 new GPU records, 0 updated', 'environ' => 'GPU', 'level' => POLLER_VERBOSITY_MEDIUM]]); +}); + +it('writes nothing for a disabled node', function () { + $inventory = new Inventory(new GpuRepository(false), new IdentityReconciler(), new FixedClock(500)); + + expect($inventory->record(repo_node(2, AdminState::Disabled), repo_snapshot('GPU-00000000-0000-4000-8000-0000000000a1'), 3)->isEmpty())->toBeTrue() + ->and($GLOBALS['__gpu_db_exec'])->toBe([]); +}); + +it('exports every node and GPU record, without serial numbers', function () { + $snapshot = repo_snapshot('GPU-00000000-0000-4000-8000-0000000000a1'); + $json = InventoryExport::json([repo_node()], [GpuRecord::discovered($snapshot->reports[0], $snapshot, 1, 0, 0)], '0.1.0-dev', 1800000000); + $document = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + + expect($document['plugin'])->toBe('gpu') + ->and($document['exported_at'])->toBe('2027-01-15T08:00:00Z') + ->and($document['nodes'][0]['host_id'])->toBe(101) + ->and($document['gpus'][0]['uuid'])->toBe('GPU-00000000-0000-4000-8000-0000000000a1') + ->and($document['gpus'][0]['tool_version'])->toBe('580.95.05') + ->and($json)->not->toContain('serial'); +}); diff --git a/tests/fixtures/identity/card-swap-reindexed.json b/tests/fixtures/identity/card-swap-reindexed.json new file mode 100644 index 0000000..13fdc57 --- /dev/null +++ b/tests/fixtures/identity/card-swap-reindexed.json @@ -0,0 +1,74 @@ +{ + "description": "A replacement card in a known slot that also comes up under a different index is still flagged: the rule matches the bus ID, because the index can change at any boot.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 0, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000c3", + "index": 1, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "presence": "present", + "missing": 1 + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 0, + "presence": "present" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000c3", + "index": 1, + "bus": "00000000:3B:00.0", + "replaces": "GPU-00000000-0000-4000-8000-0000000000a1" + } + ] +} diff --git a/tests/fixtures/identity/card-swap.json b/tests/fixtures/identity/card-swap.json new file mode 100644 index 0000000..a28523e --- /dev/null +++ b/tests/fixtures/identity/card-swap.json @@ -0,0 +1,107 @@ +{ + "description": "The card in slot 3B is replaced: a new UUID at the same node, index, and bus ID. It gets its own record, flagged as a possible replacement, and the old card goes absent with its record kept.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000c3", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1120, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000c3", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "node": 1, + "index": 0, + "bus": "00000000:3B:00.0", + "presence": "absent", + "missing": 2, + "replaces": null, + "last_seen": 1000 + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "node": 1, + "presence": "present", + "missing": 0, + "replaces": null + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000c3", + "node": 1, + "index": 0, + "bus": "00000000:3B:00.0", + "presence": "present", + "missing": 0, + "replaces": "GPU-00000000-0000-4000-8000-0000000000a1", + "first_seen": 1060 + } + ] +} diff --git a/tests/fixtures/identity/disabled-node.json b/tests/fixtures/identity/disabled-node.json new file mode 100644 index 0000000..a34303a --- /dev/null +++ b/tests/fixtures/identity/disabled-node.json @@ -0,0 +1,28 @@ +{ + "description": "A node the operator has disabled gets no records.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 3, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [] +} diff --git a/tests/fixtures/identity/driver-change.json b/tests/fixtures/identity/driver-change.json new file mode 100644 index 0000000..e44c57b --- /dev/null +++ b/tests/fixtures/identity/driver-change.json @@ -0,0 +1,53 @@ +{ + "description": "A driver upgrade changes the driver and tool versions recorded for the GPU, in place.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "570.172.08", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "570.172.08" + } + ] + }, + { + "at": 1060, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "node": 1, + "driver": "580.95.05", + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "presence": "present", + "first_seen": 1000 + } + ] +} diff --git a/tests/fixtures/identity/gpu-returns.json b/tests/fixtures/identity/gpu-returns.json new file mode 100644 index 0000000..6e0dcd3 --- /dev/null +++ b/tests/fixtures/identity/gpu-returns.json @@ -0,0 +1,99 @@ +{ + "description": "An absent GPU that is reported again returns to its own record and history.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1120, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1180, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "presence": "present" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "presence": "present", + "missing": 0, + "first_seen": 1000, + "last_seen": 1180 + } + ] +} diff --git a/tests/fixtures/identity/lost-gpu.json b/tests/fixtures/identity/lost-gpu.json new file mode 100644 index 0000000..9d1c924 --- /dev/null +++ b/tests/fixtures/identity/lost-gpu.json @@ -0,0 +1,93 @@ +{ + "description": "A GPU stops being reported. Failed and empty collections do not count as misses; it is absent after two successful collections without it, and its record stays.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1120, + "node": 1, + "failed": true + }, + { + "at": 1180, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [] + }, + { + "at": 1240, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "presence": "present", + "missing": 0, + "last_seen": 1240 + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "node": 1, + "index": 1, + "bus": "00000000:3C:00.0", + "presence": "absent", + "missing": 2, + "last_seen": 1000 + } + ] +} diff --git a/tests/fixtures/identity/node-move-confirmed.json b/tests/fixtures/identity/node-move-confirmed.json new file mode 100644 index 0000000..0615871 --- /dev/null +++ b/tests/fixtures/identity/node-move-confirmed.json @@ -0,0 +1,100 @@ +{ + "description": "An operator confirms the move. The GPU keeps its record and history at the new node, and the next collection there updates its attributes.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 2, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:5E:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "confirm_move": "GPU-00000000-0000-4000-8000-0000000000a1" + }, + { + "at": 1180, + "node": 2, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:5E:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1240, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [] + }, + { + "at": 1300, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "node": 2, + "bus": "00000000:5E:00.0", + "pending_node": 0, + "presence": "present", + "missing": 0, + "first_seen": 1000, + "last_seen": 1180 + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "node": 1, + "bus": "00000000:3B:00.0", + "replaces": null + } + ] +} diff --git a/tests/fixtures/identity/node-move-pending.json b/tests/fixtures/identity/node-move-pending.json new file mode 100644 index 0000000..a6acbee --- /dev/null +++ b/tests/fixtures/identity/node-move-pending.json @@ -0,0 +1,67 @@ +{ + "description": "A GPU appears at another node. The record stays with its node until an operator confirms the move; no second record is created.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 2, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:5E:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1120, + "node": 2, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:5E:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "node": 1, + "bus": "00000000:3B:00.0", + "pending_node": 2, + "pending_since": 1060, + "last_seen": 1000 + } + ] +} diff --git a/tests/fixtures/identity/node-move-returns.json b/tests/fixtures/identity/node-move-returns.json new file mode 100644 index 0000000..b2f5227 --- /dev/null +++ b/tests/fixtures/identity/node-move-returns.json @@ -0,0 +1,66 @@ +{ + "description": "A GPU reported elsewhere and then at its own node again drops the pending move.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 2, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:5E:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1120, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "node": 1, + "pending_node": 0, + "pending_since": 0, + "presence": "present" + } + ] +} diff --git a/tests/fixtures/identity/reboot-reorder.json b/tests/fixtures/identity/reboot-reorder.json new file mode 100644 index 0000000..71050b1 --- /dev/null +++ b/tests/fixtures/identity/reboot-reorder.json @@ -0,0 +1,78 @@ +{ + "description": "A reboot swaps the NVML indexes of two GPUs; bus IDs and UUIDs stay. Titles change, records and history do not.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 0, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 1, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "node": 1, + "index": 1, + "bus": "00000000:3B:00.0", + "presence": "present", + "missing": 0, + "replaces": null, + "first_seen": 1000, + "last_seen": 1060 + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "node": 1, + "index": 0, + "bus": "00000000:3C:00.0", + "presence": "present", + "missing": 0, + "replaces": null + } + ] +} diff --git a/tests/fixtures/identity/refused-output.json b/tests/fixtures/identity/refused-output.json new file mode 100644 index 0000000..c21a7d0 --- /dev/null +++ b/tests/fixtures/identity/refused-output.json @@ -0,0 +1,115 @@ +{ + "description": "Output that cannot be trusted is refused whole and changes nothing: a MIG instance UUID, a truncated row without a bus ID, and two rows with one UUID.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "refused": 3, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "MIG-00000000-0000-4000-8000-0000000000d4", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1120, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1180, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "presence": "present", + "missing": 0, + "last_seen": 1000 + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "presence": "present", + "missing": 0, + "last_seen": 1000 + } + ] +} diff --git a/tests/fixtures/identity/slot-move.json b/tests/fixtures/identity/slot-move.json new file mode 100644 index 0000000..a12a247 --- /dev/null +++ b/tests/fixtures/identity/slot-move.json @@ -0,0 +1,74 @@ +{ + "description": "The same card moves to another slot in the same node. Its bus ID and index change in place; no record is created and nothing is flagged.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 0, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 1, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + }, + { + "at": 1060, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "index": 0, + "bus": "00000000:3C:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": 1, + "bus": "00000000:5E:00.0", + "name": "NVIDIA Test GPU", + "driver": "580.95.05" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "node": 1, + "index": 1, + "bus": "00000000:5E:00.0", + "presence": "present", + "replaces": null + }, + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000b2", + "node": 1, + "index": 0, + "bus": "00000000:3C:00.0", + "presence": "present", + "replaces": null + } + ] +} diff --git a/tests/fixtures/identity/unavailable-values.json b/tests/fixtures/identity/unavailable-values.json new file mode 100644 index 0000000..0b5964a --- /dev/null +++ b/tests/fixtures/identity/unavailable-values.json @@ -0,0 +1,35 @@ +{ + "description": "A tool that reports the index as unavailable leaves it unknown; the GPU is still recorded by UUID.", + "source": "synthetic: hand-written identity sequences, not captured tool output; every UUID uses the reserved all-zero prefix", + "nodes": { + "1": "enabled", + "2": "enabled", + "3": "disabled" + }, + "absent_after": 2, + "steps": [ + { + "at": 1000, + "node": 1, + "tool": "nvidia-smi", + "tool_version": "580.95.05", + "gpus": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": null, + "bus": "00000000:3B:00.0", + "name": "NVIDIA Test GPU", + "driver": "" + } + ] + } + ], + "expect": [ + { + "uuid": "GPU-00000000-0000-4000-8000-0000000000a1", + "index": null, + "driver": "", + "presence": "present" + } + ] +} From a5d518a0f81f68e4b4b9bbf9c6a23efb36b0b6d1 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 00:18:01 -0800 Subject: [PATCH 04/10] feat: GPU Nodes and GPU Inventory pages Add the two plugin pages, one per realm, under Console > Management. GPU Nodes (GPU Admin) registers Cacti devices as GPU nodes, enables or disables them, removes a node that owns no GPU records, confirms or rejects pending GPU moves, and downloads every node and GPU record as JSON: the export an administrator takes before an uninstall that drops the plugin tables. Every state change is a POST that csrf-magic checks; a GET naming one is sent back without effect. No field takes a command, path, or URL. GPU Inventory (GPU View) lists GPU records only for devices Cacti's device permissions let the viewer see, and names a pending move's destination only when the viewer may see that device too. Both pages include Cacti's authentication, read request variables through Cacti's accessors, escape every tool-reported string and device description, and refuse with a message on an unsupported runtime or a disabled plugin. Refs #31, #30 Signed-off-by: Thomas Vincent --- gpu_inventory.php | 44 +++++++ gpu_nodes.php | 120 +++++++++++++++++ lib/InventoryPage.php | 116 +++++++++++++++++ lib/NodesPage.php | 151 ++++++++++++++++++++++ locales/po/cacti.pot | 212 ++++++++++++++++++++++++++++++- setup.php | 8 ++ tests/Unit/InventoryPageTest.php | 48 +++++++ tests/Unit/LifecycleUnitTest.php | 15 +++ 8 files changed, 708 insertions(+), 6 deletions(-) create mode 100644 gpu_inventory.php create mode 100644 gpu_nodes.php create mode 100644 lib/InventoryPage.php create mode 100644 lib/NodesPage.php create mode 100644 tests/Unit/InventoryPageTest.php diff --git a/gpu_inventory.php b/gpu_inventory.php new file mode 100644 index 0000000..8235481 --- /dev/null +++ b/gpu_inventory.php @@ -0,0 +1,44 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * GPU Inventory (GPU View realm). Parses on PHP 8.0; gpu_page_start() + * refuses an unsupported runtime before any plugin class loads. + */ + +chdir('../../'); +include('./include/auth.php'); +include_once('./plugins/gpu/setup.php'); + +if (!gpu_page_start()) { + exit; +} + +$gpu_page = new \Somethingwithproof\Gpu\InventoryPage( + gpu_nodes(), + gpu_gpus(), + function ($host_id) { + return is_device_allowed($host_id); + }, + new \Somethingwithproof\Gpu\SystemClock() +); + +top_header(); +$gpu_page->render(); +bottom_footer(); diff --git a/gpu_nodes.php b/gpu_nodes.php new file mode 100644 index 0000000..856cc59 --- /dev/null +++ b/gpu_nodes.php @@ -0,0 +1,120 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * GPU Nodes (GPU Admin realm). This file must parse on PHP 8.0: Cacti may + * include it on an unsupported runtime, and gpu_page_start() refuses there + * before any plugin class loads. + */ + +chdir('../../'); +include('./include/auth.php'); +include_once('./plugins/gpu/setup.php'); + +if (!gpu_page_start()) { + exit; +} + +gpu_require_post('gpu_nodes.php', array('save', 'delete', 'confirm_move', 'reject_move')); + +$gpu_nodes = gpu_nodes(); +$gpu_gpus = gpu_gpus(); +$gpu_page = new \Somethingwithproof\Gpu\NodesPage($gpu_nodes, $gpu_gpus); +$gpu_action = (string) get_nfilter_request_var('action'); + +switch ($gpu_action) { + case 'save': + $gpu_id = (int) get_filter_request_var('id'); + $gpu_host = (int) get_filter_request_var('host_id'); + $gpu_enabled = get_nfilter_request_var('enabled') === 'on'; + $gpu_node = $gpu_id > 0 ? $gpu_nodes->find($gpu_id) : null; + $gpu_errors = array(); + + if ($gpu_id > 0 && $gpu_node === null) { + header('Location: gpu_nodes.php'); + exit; + } + + if (!$gpu_nodes->deviceExists($gpu_host)) { + $gpu_errors['host_id'] = __('Device: choose an existing Cacti device.', 'gpu'); + } elseif ($gpu_nodes->hostTaken($gpu_host, $gpu_id)) { + $gpu_errors['host_id'] = __('Device: this device is already a GPU node.', 'gpu'); + } + + if ($gpu_errors !== array()) { + top_header(); + $gpu_page->renderEdit($gpu_node, $gpu_host, $gpu_enabled, $gpu_errors); + bottom_footer(); + exit; + } + + $gpu_state = $gpu_enabled ? \Somethingwithproof\Gpu\AdminState::Enabled : \Somethingwithproof\Gpu\AdminState::Disabled; + + if ($gpu_nodes->save($gpu_id, $gpu_host, $gpu_state) > 0) { + raise_message('gpu_saved', __('The GPU node was saved.', 'gpu'), MESSAGE_LEVEL_INFO); + } else { + raise_message('gpu_saved', __('The GPU node could not be saved.', 'gpu'), MESSAGE_LEVEL_ERROR); + } + + header('Location: gpu_nodes.php'); + exit; + case 'delete': + if ($gpu_nodes->delete((int) get_filter_request_var('id'))) { + raise_message('gpu_deleted', __('The GPU node was removed. Its Cacti device was left in place.', 'gpu'), MESSAGE_LEVEL_INFO); + } else { + raise_message('gpu_deleted', __('The GPU node was not removed because GPU records belong to it. Disable it instead; GPU records are never deleted.', 'gpu'), MESSAGE_LEVEL_WARN); + } + + header('Location: gpu_nodes.php'); + exit; + case 'confirm_move': + if ($gpu_gpus->confirmMove((int) get_filter_request_var('id'))) { + raise_message('gpu_move', __('The GPU now belongs to the node it was seen at, with its history.', 'gpu'), MESSAGE_LEVEL_INFO); + } + + header('Location: gpu_nodes.php'); + exit; + case 'reject_move': + if ($gpu_gpus->rejectMove((int) get_filter_request_var('id'))) { + raise_message('gpu_move', __('The GPU stays with its recorded node.', 'gpu'), MESSAGE_LEVEL_INFO); + } + + header('Location: gpu_nodes.php'); + exit; + case 'export': + $gpu_info = plugin_gpu_version(); + + header('Content-Type: application/json; charset=utf-8'); + header('Content-Disposition: attachment; filename="gpu-records-' . gmdate('Ymd-His') . '.json"'); + header('X-Content-Type-Options: nosniff'); + + print \Somethingwithproof\Gpu\InventoryExport::json($gpu_nodes->all(), $gpu_gpus->all(), $gpu_info['version'], (new \Somethingwithproof\Gpu\SystemClock())->now()); + exit; + case 'edit': + $gpu_id = (int) get_filter_request_var('id'); + + top_header(); + $gpu_page->renderEdit($gpu_id > 0 ? $gpu_nodes->find($gpu_id) : null); + bottom_footer(); + exit; + default: + top_header(); + $gpu_page->renderList(); + bottom_footer(); +} diff --git a/lib/InventoryPage.php b/lib/InventoryPage.php new file mode 100644 index 0000000..cc8afce --- /dev/null +++ b/lib/InventoryPage.php @@ -0,0 +1,116 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * The GPU Inventory page (GPU View). It shows the stored records only and + * never contacts a node. A viewer sees a GPU only when Cacti lets them see + * its node's device, and every tool-reported string is escaped where it is + * printed (REQ-UI-002). + */ +final class InventoryPage { + public const FILE = 'gpu_inventory.php'; + + /** + * @param \Closure(int): bool $deviceAllowed Cacti's device permission check for the viewer + */ + public function __construct( + private readonly NodeRepository $nodes, + private readonly GpuRepository $gpus, + private readonly \Closure $deviceAllowed, + private readonly Clock $clock, + ) { + } + + public function render(): void { + $nodes = []; + + foreach ($this->nodes->all() as $node) { + if (($this->deviceAllowed)($node->hostId)) { + $nodes[$node->id] = $node; + } + } + + $headers = [__('Node', 'gpu'), __('Index', 'gpu'), __('Name', 'gpu'), __('UUID', 'gpu'), __('PCI Bus ID', 'gpu'), __('Driver', 'gpu'), __('Reported By', 'gpu'), __('State', 'gpu'), __('Last Seen', 'gpu')]; + + html_start_box(__('GPU Inventory', 'gpu'), '100%', '', '3', 'center', ''); + + print '' . implode('', array_map('html_escape', $headers)) . ''; + + $shown = 0; + + foreach ($this->gpus->all() as $gpu) { + if (!isset($nodes[$gpu->nodeId])) { + continue; + } + + print '' . implode('', array_map('html_escape', $this->row($gpu, $nodes))) . ''; + $shown++; + } + + if ($shown === 0) { + print '' . html_escape(__('No GPUs recorded yet. GPUs appear here once collection, which arrives in a later release, reports them.', 'gpu')) . ''; + } + + html_end_box(); + } + + /** + * The cells of one GPU's row, as plain text. + * + * @param array $nodes the nodes the viewer may see, by id + * @return list + */ + public function row(GpuRecord $gpu, array $nodes): array { + $state = [$gpu->presence === Presence::Present ? __('Present', 'gpu') : __('Absent', 'gpu')]; + + if ($gpu->possibleReplacement()) { + $state[] = __('possible replacement of GPU record %d', $gpu->replacesGpuId, 'gpu'); + } + + if ($gpu->movePending()) { + // The destination is named only to a viewer who may see it. + $state[] = isset($nodes[$gpu->pendingNodeId]) ? __('seen at %s, move not confirmed', $nodes[$gpu->pendingNodeId]->description, 'gpu') : __('seen at another node, move not confirmed', 'gpu'); + } + + return [ + $nodes[$gpu->nodeId]->description, + $gpu->index === null ? '-' : (string) $gpu->index, + $gpu->name, + $gpu->uuid, + $gpu->pciBusId, + $gpu->driverVersion, + trim($gpu->tool . ' ' . $gpu->toolVersion), + implode('; ', $state), + $gpu->lastSeen > 0 ? $this->age($gpu->lastSeen) : __('Never', 'gpu'), + ]; + } + + private function age(int $time): string { + $seconds = max(0, $this->clock->now() - $time); + + return match (true) { + $seconds < 120 => __('%d seconds ago', $seconds, 'gpu'), + $seconds < 7200 => __('%d minutes ago', intdiv($seconds, 60), 'gpu'), + $seconds < 172800 => __('%d hours ago', intdiv($seconds, 3600), 'gpu'), + default => __('%d days ago', intdiv($seconds, 86400), 'gpu'), + }; + } +} diff --git a/lib/NodesPage.php b/lib/NodesPage.php new file mode 100644 index 0000000..075cae6 --- /dev/null +++ b/lib/NodesPage.php @@ -0,0 +1,151 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Gpu; + +/** + * The GPU Nodes page (GPU Admin): register Cacti devices as GPU nodes, + * confirm or reject GPU moves, and export the records. Every action that + * changes state is a POST form, and csrf-magic adds its token to each + * (REQ-UI-004). Nothing here takes a command, path, or URL. + */ +final class NodesPage { + public const FILE = 'gpu_nodes.php'; + + public function __construct( + private readonly NodeRepository $nodes, + private readonly GpuRepository $gpus, + ) { + } + + public function renderList(): void { + $nodes = $this->nodes->all(); + $counts = []; + + foreach ($this->gpus->all() as $gpu) { + $counts[$gpu->nodeId][$gpu->presence->value] = ($counts[$gpu->nodeId][$gpu->presence->value] ?? 0) + 1; + } + + html_start_box(__('GPU Nodes', 'gpu'), '100%', '', '3', 'center', self::FILE . '?action=edit'); + + print '' . implode('', array_map('html_escape', [ + __('Device', 'gpu'), __('State', 'gpu'), __('GPUs Present', 'gpu'), __('GPUs Absent', 'gpu'), __('Actions', 'gpu'), + ])) . ''; + + if ($nodes === []) { + print '' . html_escape(__('No GPU nodes yet. Add a Cacti device that has GPUs.', 'gpu')) . ''; + } + + foreach ($nodes as $node) { + $label = $node->deviceExists ? $node->description : __('Deleted device %d', $node->hostId, 'gpu'); + + print '' + . '' . html_escape($label) . '' + . '' . html_escape($node->enabled() ? __('Enabled', 'gpu') : __('Disabled', 'gpu')) . '' + . '' . ($counts[$node->id][Presence::Present->value] ?? 0) . '' + . '' . ($counts[$node->id][Presence::Absent->value] ?? 0) . '' + . '' . $this->actionForm($node->id, 'delete', __('Delete', 'gpu')) . '' + . ''; + } + + html_end_box(); + + $this->renderPendingMoves($nodes); + + html_start_box(__('Export', 'gpu'), '100%', '', '3', 'center', ''); + print '' . html_escape(__('Download every node and GPU record as JSON. Take an export before an uninstall that drops the plugin tables.', 'gpu')) + . ' ' . html_escape(__('Export Records', 'gpu')) . ''; + html_end_box(); + } + + /** + * @param list $nodes + */ + private function renderPendingMoves(array $nodes): void { + $moves = $this->gpus->pendingMoves(); + + if ($moves === []) { + return; + } + + $names = []; + + foreach ($nodes as $node) { + $names[$node->id] = $node->description; + } + + html_start_box(__('GPU Moves Awaiting Confirmation', 'gpu'), '100%', '', '3', 'center', ''); + + print '' . implode('', array_map('html_escape', [ + __('UUID', 'gpu'), __('Name', 'gpu'), __('Recorded At', 'gpu'), __('Seen At', 'gpu'), __('Actions', 'gpu'), + ])) . ''; + + foreach ($moves as $gpu) { + print '' + . '' . html_escape($gpu->uuid) . '' + . '' . html_escape($gpu->name) . '' + . '' . html_escape($names[$gpu->nodeId] ?? '-') . '' + . '' . html_escape($names[$gpu->pendingNodeId] ?? '-') . '' + . '' . $this->actionForm($gpu->id, 'confirm_move', __('Confirm Move', 'gpu')) . ' ' . $this->actionForm($gpu->id, 'reject_move', __('Reject', 'gpu')) . '' + . ''; + } + + html_end_box(); + } + + /** + * @param array $errors field => message + */ + public function renderEdit(?Node $node, int $hostId = 0, ?bool $enabled = null, array $errors = []): void { + $devices = $this->nodes->devicesFor($node->id ?? 0); + $current = $hostId > 0 ? $hostId : ($node->hostId ?? 0); + $enabled ??= $node?->enabled() ?? true; + + print '
'; + html_start_box($node === null ? __('New GPU Node', 'gpu') : __('GPU Node: %s', html_escape($node->description), 'gpu'), '100%', '', '3', 'center', ''); + + foreach ($errors as $message) { + print '' . html_escape($message) . ''; + } + + print ''; + print ''; + + html_end_box(); + + print '' + . '' + . '' + . '
'; + } + + private function actionForm(int $id, string $action, string $label): string { + return '
' + . '' + . '' + . '' + . '
'; + } +} diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 161be61..d54ddb6 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -16,20 +16,220 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -#: lib/Pages.php -msgid "GPU View" +#: gpu_nodes.php +msgid "Device: choose an existing Cacti device." msgstr "" -#: lib/Pages.php -msgid "GPU Admin" +#: gpu_nodes.php +msgid "Device: this device is already a GPU node." msgstr "" -#: lib/Pages.php +#: gpu_nodes.php +msgid "The GPU node was saved." +msgstr "" + +#: gpu_nodes.php +msgid "The GPU node could not be saved." +msgstr "" + +#: gpu_nodes.php +msgid "The GPU node was removed. Its Cacti device was left in place." +msgstr "" + +#: gpu_nodes.php +msgid "The GPU node was not removed because GPU records belong to it. Disable it instead; GPU records are never deleted." +msgstr "" + +#: gpu_nodes.php +msgid "The GPU now belongs to the node it was seen at, with its history." +msgstr "" + +#: gpu_nodes.php +msgid "The GPU stays with its recorded node." +msgstr "" + +#: lib/InventoryPage.php +msgid "Driver" +msgstr "" + +#: lib/InventoryPage.php +msgid "Index" +msgstr "" + +#: lib/InventoryPage.php +msgid "Last Seen" +msgstr "" + +#: lib/InventoryPage.php lib/NodesPage.php +msgid "Name" +msgstr "" + +#: lib/InventoryPage.php +msgid "Node" +msgstr "" + +#: lib/InventoryPage.php +msgid "PCI Bus ID" +msgstr "" + +#: lib/InventoryPage.php +msgid "Reported By" +msgstr "" + +#: lib/InventoryPage.php lib/NodesPage.php +msgid "State" +msgstr "" + +#: lib/InventoryPage.php lib/NodesPage.php +msgid "UUID" +msgstr "" + +#: lib/InventoryPage.php lib/Pages.php +msgid "GPU Inventory" +msgstr "" + +#: lib/InventoryPage.php +msgid "No GPUs recorded yet. GPUs appear here once collection, which arrives in a later release, reports them." +msgstr "" + +#: lib/InventoryPage.php +msgid "Absent" +msgstr "" + +#: lib/InventoryPage.php +msgid "Present" +msgstr "" + +#: lib/InventoryPage.php +#, php-format +msgid "possible replacement of GPU record %d" +msgstr "" + +#: lib/InventoryPage.php +#, php-format +msgid "seen at %s, move not confirmed" +msgstr "" + +#: lib/InventoryPage.php +msgid "seen at another node, move not confirmed" +msgstr "" + +#: lib/InventoryPage.php +msgid "Never" +msgstr "" + +#: lib/InventoryPage.php +#, php-format +msgid "%d seconds ago" +msgstr "" + +#: lib/InventoryPage.php +#, php-format +msgid "%d minutes ago" +msgstr "" + +#: lib/InventoryPage.php +#, php-format +msgid "%d hours ago" +msgstr "" + +#: lib/InventoryPage.php +#, php-format +msgid "%d days ago" +msgstr "" + +#: lib/NodesPage.php lib/Pages.php msgid "GPU Nodes" msgstr "" +#: lib/NodesPage.php +msgid "Actions" +msgstr "" + +#: lib/NodesPage.php +msgid "Device" +msgstr "" + +#: lib/NodesPage.php +msgid "GPUs Absent" +msgstr "" + +#: lib/NodesPage.php +msgid "GPUs Present" +msgstr "" + +#: lib/NodesPage.php +msgid "No GPU nodes yet. Add a Cacti device that has GPUs." +msgstr "" + +#: lib/NodesPage.php +#, php-format +msgid "Deleted device %d" +msgstr "" + +#: lib/NodesPage.php +msgid "Disabled" +msgstr "" + +#: lib/NodesPage.php +msgid "Enabled" +msgstr "" + +#: lib/NodesPage.php +msgid "Delete" +msgstr "" + +#: lib/NodesPage.php +msgid "Export" +msgstr "" + +#: lib/NodesPage.php +msgid "Download every node and GPU record as JSON. Take an export before an uninstall that drops the plugin tables." +msgstr "" + +#: lib/NodesPage.php +msgid "Export Records" +msgstr "" + +#: lib/NodesPage.php +msgid "GPU Moves Awaiting Confirmation" +msgstr "" + +#: lib/NodesPage.php +msgid "Recorded At" +msgstr "" + +#: lib/NodesPage.php +msgid "Seen At" +msgstr "" + +#: lib/NodesPage.php +msgid "Confirm Move" +msgstr "" + +#: lib/NodesPage.php +msgid "Reject" +msgstr "" + +#: lib/NodesPage.php +#, php-format +msgid "GPU Node: %s" +msgstr "" + +#: lib/NodesPage.php +msgid "New GPU Node" +msgstr "" + +#: lib/NodesPage.php +msgid "Save" +msgstr "" + #: lib/Pages.php -msgid "GPU Inventory" +msgid "GPU View" +msgstr "" + +#: lib/Pages.php +msgid "GPU Admin" msgstr "" #: lib/Settings.php diff --git a/setup.php b/setup.php index d82fb77..256cf05 100644 --- a/setup.php +++ b/setup.php @@ -142,6 +142,14 @@ function gpu_settings(): \Somethingwithproof\Gpu\Settings { return (new \Somethingwithproof\Gpu\SettingsRepository(false))->load(); } +function gpu_nodes(): \Somethingwithproof\Gpu\NodeRepository { + return new \Somethingwithproof\Gpu\NodeRepository(false, new \Somethingwithproof\Gpu\SystemClock()); +} + +function gpu_gpus(): \Somethingwithproof\Gpu\GpuRepository { + return new \Somethingwithproof\Gpu\GpuRepository(false); +} + /** * Bring the schema, hooks, and realms up to the code's version. * diff --git a/tests/Unit/InventoryPageTest.php b/tests/Unit/InventoryPageTest.php new file mode 100644 index 0000000..6b04507 --- /dev/null +++ b/tests/Unit/InventoryPageTest.php @@ -0,0 +1,48 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Gpu\AdminState; +use Somethingwithproof\Gpu\FixedClock; +use Somethingwithproof\Gpu\GpuRecord; +use Somethingwithproof\Gpu\GpuRepository; +use Somethingwithproof\Gpu\InventoryPage; +use Somethingwithproof\Gpu\Node; +use Somethingwithproof\Gpu\NodeRepository; +use Somethingwithproof\Gpu\Presence; +use Somethingwithproof\Gpu\Vendor; + +function page_node(int $id): Node { + return new Node($id, 100 + $id, AdminState::Enabled, 'node' . $id, true, 0, 0); +} + +it('names a pending destination only to a viewer allowed to see it', function () { + $page = new InventoryPage(new NodeRepository(false, new FixedClock(0)), new GpuRepository(false), static fn (int $host): bool => true, new FixedClock(1000)); + $gpu = new GpuRecord(1, Vendor::Nvidia, 'GPU-00000000-0000-4000-8000-0000000000a1', 1, 0, '00000000:3B:00.0', 'x', '580.95.05', 'nvidia-smi', '580.95.05', Presence::Present, 0, 9, 2, 900, 100, 940); + $nodes = [1 => page_node(1), 2 => page_node(2)]; + + $seen = $page->row($gpu, $nodes); + $hidden = $page->row($gpu, [1 => page_node(1)]); + + expect($seen[0])->toBe('node1') + ->and($seen[2])->toBe('x') + ->and($seen[6])->toBe('nvidia-smi 580.95.05') + ->and($seen[7])->toBe('Present; possible replacement of GPU record 9; seen at node2, move not confirmed') + ->and($seen[8])->toBe('60 seconds ago') + ->and($hidden[7])->toBe('Present; possible replacement of GPU record 9; seen at another node, move not confirmed'); +}); diff --git a/tests/Unit/LifecycleUnitTest.php b/tests/Unit/LifecycleUnitTest.php index 3b08d16..f7cf3fe 100644 --- a/tests/Unit/LifecycleUnitTest.php +++ b/tests/Unit/LifecycleUnitTest.php @@ -76,6 +76,21 @@ } }); +it('lists every page script the plugin ships in a realm', function () { + $root = dirname(__DIR__, 2); + $scripts = array_map('basename', glob($root . '/gpu*.php')); + + expect($scripts)->not->toBeEmpty(); + + foreach ($scripts as $script) { + expect(in_array($script, Pages::files(), true))->toBeTrue($script); + } + + foreach (Pages::files() as $file) { + expect(is_file($root . '/' . $file))->toBeTrue($file); + } +}); + it('gives every menu page a breadcrumb under the console', function () { $nav = Pages::navigation(); From 4db3c23014d1bbbb74c0891e1caf9d700e96f007 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 00:19:06 -0800 Subject: [PATCH 05/10] test: lifecycle, refusal, and page permission checks against Cacti Drive the plugin through Cacti's own plugin API in fresh PHP processes, against a disposable database, the way plugin_cloud's foundation does. - The lifecycle suite installs, enables, disables, upgrades, interrupts and finishes an upgrade, refuses a newer schema, re-registers lost hooks and realms, and uninstalls with and without kept tables on both the supported and the refused path. It also replays the identity rules through the real repositories, including the unique key that refuses a second record for one UUID. - php-guard-check.php proves the PHP 8.2 refusal on a real install: below 8.2 nothing is created or loaded and registered hooks stay quiet; on 8.2 install and enable succeed. - page-check.php shows core pages still load, and plugin pages show the refusal, on an unsupported PHP. - page-permissions.php requests both pages as an anonymous user, a user without a plugin realm, a GPU View user with device permissions, and an admin; checks escaping of GPU names and device descriptions; and shows that GET and token-less POST actions have no effect while the same action with the token works. Refs #34, #29, #30, #31, #33 Signed-off-by: Thomas Vincent --- phpunit-integration.xml | 17 ++ tests/Integration/LifecycleTest.php | 207 +++++++++++++++++++++++ tests/bin/lifecycle.php | 246 ++++++++++++++++++++++++++++ tests/bin/page-check.php | 89 ++++++++++ tests/bin/page-permissions.php | 236 ++++++++++++++++++++++++++ tests/bin/php-guard-check.php | 125 ++++++++++++++ tests/bootstrap-integration.php | 67 ++++++++ 7 files changed, 987 insertions(+) create mode 100644 phpunit-integration.xml create mode 100644 tests/Integration/LifecycleTest.php create mode 100644 tests/bin/lifecycle.php create mode 100644 tests/bin/page-check.php create mode 100644 tests/bin/page-permissions.php create mode 100644 tests/bin/php-guard-check.php create mode 100644 tests/bootstrap-integration.php diff --git a/phpunit-integration.xml b/phpunit-integration.xml new file mode 100644 index 0000000..eca3820 --- /dev/null +++ b/phpunit-integration.xml @@ -0,0 +1,17 @@ + + + + + + + + + tests/Integration + + + diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php new file mode 100644 index 0000000..42d0885 --- /dev/null +++ b/tests/Integration/LifecycleTest.php @@ -0,0 +1,207 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +// The version INFO declares, which Cacti records as the installed version. +define('GPU_VERSION', (string) (parse_ini_file(dirname(__DIR__, 2) . '/INFO', true)['info']['version'] ?? '')); + +const GPU_TABLES = ['plugin_gpu_gpu', 'plugin_gpu_node']; + +const GPU_HOOKS = ['config_arrays', 'config_settings', 'draw_navigation_text']; + +beforeEach(function () { + lifecycle('reset'); +}); + +afterAll(function () { + lifecycle('reset'); +}); + +it('installs fresh with tracked tables, hooks, and both realms, leaving the plugin disabled', function () { + $state = lifecycle('install'); + + expect($state['plugin']['status'])->toEqual('4') + ->and($state['plugin']['version'])->toEqual(GPU_VERSION) + ->and($state['schema'])->toEqual('1') + ->and(array_keys($state['tables']))->toBe(GPU_TABLES) + ->and($state['tracked'])->toBe(GPU_TABLES) + ->and(array_keys($state['hooks']))->toBe(GPU_HOOKS) + ->and($state['realms'])->toEqual([ + 'gpu_inventory.php' => 'GPU View', + 'gpu_nodes.php' => 'GPU Admin', + ]) + ->and($state['admin'])->toBe(2); +}); + +it('enables and disables through core, keeping records on disable', function () { + lifecycle('install'); + lifecycle('seed'); + + $enabled = lifecycle('enable'); + expect($enabled['plugin']['status'])->toEqual('1') + ->and(array_values(array_unique(array_map('strval', $enabled['hooks']))))->toBe(['1']); + + $disabled = lifecycle('disable'); + expect($disabled['plugin']['status'])->toEqual('4') + ->and($disabled['tables'])->toBe(['plugin_gpu_gpu' => 1, 'plugin_gpu_node' => 1]); +}); + +it('upgrades from an older recorded version and is idempotent on repeated runs', function () { + lifecycle('install'); + lifecycle('seed'); + lifecycle('set_version', '0.0'); + + $first = lifecycle('upgrade'); + expect($first['result'])->toBeTrue() + ->and($first['plugin']['version'])->toEqual(GPU_VERSION); + + foreach ([lifecycle('upgrade'), lifecycle('upgrade')] as $run) { + expect($run['result'])->toBeTrue() + ->and($run['tables'])->toBe($first['tables']) + ->and($run['hooks'])->toBe($first['hooks']) + ->and($run['realms'])->toBe($first['realms']) + ->and($run['tracked'])->toBe(GPU_TABLES) + ->and($run['plugin'])->toBe($first['plugin']); + } + + expect($first['tables'])->toBe(['plugin_gpu_gpu' => 1, 'plugin_gpu_node' => 1]); +}); + +it('re-registers hooks and realms that went missing', function () { + lifecycle('install'); + + $missing = lifecycle('drop_registrations'); + expect($missing['hooks'])->toBe([]); + + $state = lifecycle('upgrade'); + + expect($state['result'])->toBeTrue() + ->and(array_keys($state['hooks']))->toBe(GPU_HOOKS) + ->and($state['realms'])->toHaveCount(2); +}); + +it('finishes an upgrade that was interrupted after creating only some tables', function () { + lifecycle('install'); + lifecycle('seed'); + lifecycle('drop_table', 'plugin_gpu_gpu'); + lifecycle('set_schema', '0'); + lifecycle('set_version', '0.0'); + + $state = lifecycle('upgrade'); + + expect($state['result'])->toBeTrue() + ->and(array_keys($state['tables']))->toBe(GPU_TABLES) + ->and($state['tables']['plugin_gpu_node'])->toBe(1) + ->and($state['schema'])->toEqual('1') + ->and($state['plugin']['version'])->toEqual(GPU_VERSION); +}); + +it('does not advance past a migration that did not run', function () { + lifecycle('install'); + lifecycle('set_schema', '0'); + + $stopped = lifecycle('migrate_through', '0'); + expect($stopped['result'])->toBeTrue() + ->and($stopped['schema'])->toEqual('0'); + + $finished = lifecycle('upgrade'); + expect($finished['schema'])->toEqual('1'); +}); + +it('refuses a schema newer than the code and leaves the recorded version alone', function () { + lifecycle('install'); + lifecycle('set_schema', '99'); + lifecycle('set_version', '0.0'); + + $state = lifecycle('upgrade'); + + expect($state['result'])->toBeFalse() + ->and($state['plugin']['version'])->toEqual('0.0') + ->and($state['schema'])->toEqual('99'); +}); + +it('keeps tables on uninstall by default, and drops them only when the box was cleared', function () { + lifecycle('install'); + lifecycle('seed'); + + $kept = lifecycle('uninstall'); + expect(array_keys($kept['tables']))->toBe(GPU_TABLES) + ->and($kept['tables']['plugin_gpu_gpu'])->toBe(1) + ->and($kept['tracked'])->toBe([]) + ->and($kept['hooks'])->toBe([]) + ->and($kept['realms'])->toBe([]); + + // A reinstall reuses the kept tables and their rows. + $reinstalled = lifecycle('install'); + expect($reinstalled['plugin']['status'])->toEqual('4') + ->and($reinstalled['tables']['plugin_gpu_gpu'])->toBe(1) + ->and($reinstalled['tracked'])->toBe(GPU_TABLES); + + lifecycle('set_setting', 'gpu_uninstall_keep_tables='); + + $dropped = lifecycle('uninstall'); + expect($dropped['plugin'])->toBeEmpty() + ->and($dropped['tables'])->toBe([]) + ->and($dropped['schema'])->toBeEmpty(); +}); + +it('honours keep tables on uninstall when the runtime is refused', function () { + lifecycle('install'); + lifecycle('seed'); + + $kept = lifecycle('uninstall_unbooted'); + expect($kept['tables']['plugin_gpu_gpu'])->toBe(1) + ->and($kept['tracked'])->toBe([]); + + lifecycle('reset'); + lifecycle('install'); + lifecycle('set_setting', 'gpu_uninstall_keep_tables='); + + $dropped = lifecycle('uninstall_unbooted'); + expect($dropped['tables'])->toBe([]) + ->and($dropped['schema'])->toBeEmpty(); +}); + +it('grants realms on install but never on a repair a viewer triggers', function () { + expect(lifecycle('install')['admin'])->toBe(2); + + $repair = lifecycle('repair_as_viewer'); + expect($repair['realms'])->toHaveCount(2) + ->and($repair['result'])->toBe(['viewer_realms' => 0]); +}); + +it('keeps GPU identity rules against the real schema', function () { + lifecycle('install'); + + $r = lifecycle('identity_flow')['result']; + + expect($r['created'])->toBe([2, 1, 0]) + ->and($r['confirmed'])->toBeTrue() + ->and($r['confirmed_twice'])->toBeFalse() + // The unique key refuses a second record for a stored UUID. + ->and($r['duplicate_ok'])->toBeFalse() + ->and($r['rows'])->toBe([ + 'a1' => ['node' => 'one', 'presence' => 'present', 'missing' => 1, 'replaces' => '', 'pending' => 0, 'bus' => '00000000:3B:00.0'], + 'b2' => ['node' => 'two', 'presence' => 'present', 'missing' => 0, 'replaces' => '', 'pending' => 0, 'bus' => '00000000:3C:00.0'], + 'c3' => ['node' => 'one', 'presence' => 'present', 'missing' => 0, 'replaces' => 'a1', 'pending' => 0, 'bus' => '00000000:3B:00.0'], + ]) + // A node that owns GPU records is not deleted; an empty one is. + ->and($r['delete_owner'])->toBeFalse() + ->and($r['delete_empty'])->toBeTrue() + ->and($r['nodes_left'])->toBe(2); +}); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php new file mode 100644 index 0000000..ebccbbf --- /dev/null +++ b/tests/bin/lifecycle.php @@ -0,0 +1,246 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Drive the plugin lifecycle through Cacti's own plugin API in a fresh PHP + * process, the way plugins.php and cli/plugin_manage.php do, and print the + * resulting state as JSON. Used by tests/Integration. Disposable databases + * only. + * + * php plugins/gpu/tests/bin/lifecycle.php [argument] + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/plugins.php'); +require_once($config['base_path'] . '/lib/poller.php'); + +if (getenv('GPU_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Set GPU_TEST_DATABASE=disposable\n"); + exit(2); +} + +$action = isset($argv[1]) ? $argv[1] : 'state'; +$argument = isset($argv[2]) ? $argv[2] : ''; +$result = null; + +ob_start(); + +switch ($action) { + case 'reset': + api_plugin_uninstall('gpu'); + + foreach (db_fetch_assoc("SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'plugin\\_gpu\\_%'") as $row) { + db_execute('DROP TABLE `' . $row['t'] . '`'); + } + + db_execute("DELETE FROM settings WHERE name LIKE 'gpu\\_%'"); + db_execute("DELETE FROM plugin_db_changes WHERE plugin = 'gpu'"); + + break; + case 'install': + api_plugin_install('gpu'); + + break; + case 'enable': + api_plugin_enable('gpu'); + + break; + case 'disable': + api_plugin_disable('gpu'); + + break; + case 'uninstall': + api_plugin_uninstall('gpu'); + + break; + case 'upgrade': + include_once($config['base_path'] . '/plugins/gpu/setup.php'); + $result = plugin_gpu_upgrade(); + + break; + case 'migrate_through': + // Stop after the given migration, as an upgrade killed part way would. + include_once($config['base_path'] . '/plugins/gpu/setup.php'); + gpu_boot(); + $result = (new \Somethingwithproof\Gpu\Schema(false))->migrate((int) $argument); + + break; + case 'set_version': + db_execute_prepared("UPDATE plugin_config SET version = ? WHERE directory = 'gpu'", array($argument)); + + break; + case 'set_schema': + db_execute_prepared("REPLACE INTO settings (name, value) VALUES ('gpu_schema_version', ?)", array($argument)); + + break; + case 'set_setting': + list($name, $value) = explode('=', $argument, 2); + db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', array($name, $value)); + + break; + case 'drop_registrations': + // What a failed hook registration on an earlier request leaves. + db_execute("DELETE FROM plugin_hooks WHERE name = 'gpu'"); + db_execute("DELETE FROM plugin_realms WHERE plugin = 'gpu'"); + + break; + case 'drop_table': + db_execute('DROP TABLE IF EXISTS `' . preg_replace('/[^a-z_]/', '', $argument) . '`'); + + break; + case 'seed': + // A node and a GPU record, so table drops and keeps are visible. + db_execute("INSERT INTO plugin_gpu_node (host_id, admin_state) VALUES (9001, 'enabled')"); + db_execute_prepared("INSERT INTO plugin_gpu_gpu (vendor, uuid, node_id, pci_bus_id) VALUES ('nvidia', 'GPU-00000000-0000-4000-8000-0000000000a1', ?, '00000000:3B:00.0')", array(db_fetch_insert_id())); + + break; + case 'identity_flow': + // The identity rules against MariaDB through the real repositories: + // a replacement, a pending move, its confirmation, the unique key, + // and the node delete guard (REQ-ID-001 to REQ-ID-005). + include_once($config['base_path'] . '/plugins/gpu/setup.php'); + gpu_boot(); + + $clock = new \Somethingwithproof\Gpu\FixedClock(1800000000); + $nodes = new \Somethingwithproof\Gpu\NodeRepository(false, $clock); + $gpus = new \Somethingwithproof\Gpu\GpuRepository(false); + $inventory = new \Somethingwithproof\Gpu\Inventory($gpus, new \Somethingwithproof\Gpu\IdentityReconciler(), $clock); + $enabled = \Somethingwithproof\Gpu\AdminState::Enabled; + + $one = $nodes->find($nodes->save(0, 9001, $enabled)); + $two = $nodes->find($nodes->save(0, 9002, $enabled)); + $three = $nodes->save(0, 9003, $enabled); + + $uuid = function ($suffix) { + return 'GPU-00000000-0000-4000-8000-0000000000' . $suffix; + }; + + $snapshot = function (array $gpus) { + $reports = array(); + + foreach ($gpus as $gpu) { + $reports[] = \Somethingwithproof\Gpu\GpuReport::create(\Somethingwithproof\Gpu\Vendor::Nvidia, $gpu[0], $gpu[1], $gpu[2], 'NVIDIA Test GPU', '580.95.05'); + } + + return \Somethingwithproof\Gpu\GpuSnapshot::create('nvidia-smi', '580.95.05', $reports); + }; + + $steps = array(); + + $steps[] = count($inventory->record($one, $snapshot(array(array($uuid('a1'), 0, '00000000:3B:00.0'), array($uuid('b2'), 1, '00000000:3C:00.0'))), 2)->created); + $clock->advance(60); + $steps[] = count($inventory->record($one, $snapshot(array(array($uuid('c3'), 0, '0000:3b:00.0'), array($uuid('b2'), 1, '00000000:3C:00.0'))), 2)->created); + $clock->advance(60); + $steps[] = count($inventory->record($two, $snapshot(array(array($uuid('b2'), 0, '00000000:5E:00.0'))), 2)->created); + + $b = null; + + foreach ($gpus->pendingMoves() as $record) { + $b = $record->id; + } + + $confirmed = $b !== null && $gpus->confirmMove($b); + $confirmedTwice = $b !== null && $gpus->confirmMove($b); + + // A second record for a stored UUID must fail at the unique key. + $copy = $snapshot(array(array($uuid('a1'), 3, '00000000:AF:00.0'))); + $duplicate = $gpus->apply(new \Somethingwithproof\Gpu\Reconciliation(array(\Somethingwithproof\Gpu\GpuRecord::discovered($copy->reports[0], $copy, $two->id, 0, 0)))); + + $rows = array(); + $ids = array_column(db_fetch_assoc('SELECT id, uuid FROM plugin_gpu_gpu'), 'uuid', 'id'); + + foreach ($gpus->all() as $record) { + $rows[substr($record->uuid, -2)] = array( + 'node' => $record->nodeId === $one->id ? 'one' : ($record->nodeId === $two->id ? 'two' : 'other'), + 'presence' => $record->presence->value, + 'missing' => $record->missingCount, + 'replaces' => $record->replacesGpuId > 0 ? substr($ids[$record->replacesGpuId], -2) : '', + 'pending' => $record->pendingNodeId, + 'bus' => $record->pciBusId, + ); + } + + ksort($rows); + + $result = array( + 'created' => $steps, + 'confirmed' => $confirmed, + 'confirmed_twice' => $confirmedTwice, + 'duplicate_ok' => $duplicate, + 'rows' => $rows, + 'delete_owner' => $nodes->delete($one->id), + 'delete_empty' => $nodes->delete($three), + 'nodes_left' => count($nodes->all()), + ); + + break; + case 'uninstall_unbooted': + // What core does on uninstall when gpu_boot() refuses: the PHP 8.0 + // fallback, then core drops whatever is still tracked. + include_once($config['base_path'] . '/plugins/gpu/include/unbooted-uninstall.php'); + gpu_uninstall_unbooted(); + api_plugin_db_changes_remove('gpu'); + api_plugin_remove_hooks('gpu'); + api_plugin_remove_realms('gpu'); + db_execute("DELETE FROM plugin_config WHERE directory = 'gpu'"); + + break; + case 'repair_as_viewer': + // A viewer opens a plugin page after the realm rows went missing. + db_execute("DELETE FROM user_auth WHERE username = 'gpuviewer'"); + db_execute("INSERT INTO user_auth (username, password, realm, full_name, enabled) VALUES ('gpuviewer', '', 0, 'viewer', 'on')"); + $viewer = (int) db_fetch_insert_id(); + db_execute("DELETE FROM plugin_realms WHERE plugin = 'gpu'"); + db_execute("DELETE FROM plugin_hooks WHERE name = 'gpu'"); + $_SESSION['sess_user_id'] = $viewer; + db_execute("REPLACE INTO settings (name, value) VALUES ('admin_user', '0')"); + include_once($config['base_path'] . '/plugins/gpu/setup.php'); + plugin_gpu_upgrade(); + $result = array('viewer_realms' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM user_auth_realm WHERE user_id = ?', array($viewer))); + db_execute("REPLACE INTO settings (name, value) VALUES ('admin_user', '1')"); + + break; + case 'state': + break; + default: + fwrite(STDERR, "Unknown action $action\n"); + exit(2); +} + +$output = ob_get_clean(); + +$tables = array(); + +foreach (db_fetch_assoc("SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'plugin\\_gpu\\_%' ORDER BY TABLE_NAME") as $row) { + $tables[$row['t']] = (int) db_fetch_cell('SELECT COUNT(*) FROM `' . $row['t'] . '`'); +} + +print json_encode(array( + 'result' => $result, + 'output' => $output, + 'plugin' => db_fetch_row("SELECT status, version FROM plugin_config WHERE directory = 'gpu'"), + 'schema' => db_fetch_cell("SELECT value FROM settings WHERE name = 'gpu_schema_version'"), + 'hooks' => array_column(db_fetch_assoc("SELECT hook, status FROM plugin_hooks WHERE name = 'gpu' ORDER BY hook"), 'status', 'hook'), + 'realms' => array_column(db_fetch_assoc("SELECT file, display FROM plugin_realms WHERE plugin = 'gpu' ORDER BY file"), 'display', 'file'), + 'admin' => (int) db_fetch_cell("SELECT COUNT(*) FROM user_auth_realm AS uar INNER JOIN plugin_realms AS pr ON pr.id + 100 = uar.realm_id WHERE pr.plugin = 'gpu' AND uar.user_id = 1"), + 'tracked' => array_column(db_fetch_assoc("SELECT `table` FROM plugin_db_changes WHERE plugin = 'gpu' AND method = 'create' ORDER BY `table`"), 'table'), + 'tables' => $tables, +), JSON_PRETTY_PRINT) . PHP_EOL; diff --git a/tests/bin/page-check.php b/tests/bin/page-check.php new file mode 100644 index 0000000..d74fb45 --- /dev/null +++ b/tests/bin/page-check.php @@ -0,0 +1,89 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Log in as the Cacti admin user over HTTP and request a list of pages, + * failing on any non-200 response, PHP error text, or missing Cacti footer. + * Used to show that core pages keep loading with the plugin installed on an + * unsupported PHP. Disposable databases only: it resets the admin password. + * Must parse on PHP 8.0. + * + * php plugins/gpu/tests/bin/page-check.php http://127.0.0.1:8080/cacti/ index.php host.php ... + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); + +if (getenv('GPU_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Refusing to reset the admin password: set GPU_TEST_DATABASE=disposable\n"); + exit(2); +} + +$base = rtrim($argv[1], '/') . '/'; +$pages = array_slice($argv, 2); +$password = 'Gpu-' . bin2hex(random_bytes(6)); + +db_execute_prepared("UPDATE user_auth SET password = ?, must_change_password = '' WHERE id = 1", array(password_hash($password, PASSWORD_DEFAULT))); + +$jar = tempnam(sys_get_temp_dir(), 'page'); + +function page_get($url, $jar, $post = null) { + $ch = curl_init($url); + + curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEJAR => $jar, CURLOPT_COOKIEFILE => $jar, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 60)); + + if ($post !== null) { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); + } + + $body = (string) curl_exec($ch); + + return array((int) curl_getinfo($ch, CURLINFO_HTTP_CODE), $body); +} + +list(, $login) = page_get($base . 'index.php', $jar); +preg_match('/csrfMagicToken\s*=\s*"([^"]+)"/', $login, $match); +page_get($base . 'index.php', $jar, array('__csrf_magic' => isset($match[1]) ? $match[1] : '', 'action' => 'login', 'login_username' => 'admin', 'login_password' => $password)); + +$failures = 0; + +foreach ($pages as $page) { + list($code, $body) = page_get($base . $page, $jar); + + $error = preg_match('/(Fatal error|Parse error|Warning:|Uncaught)/', $body, $m) ? $m[1] : ''; + $ok = $code === 200 && $error === '' && strpos($body, 'logout.php') !== false; + + // A plugin page on a refused runtime must say why instead of failing. + if (strpos($page, 'plugins/gpu/') === 0) { + $refused = preg_match('/The GPU plugin (requires PHP [0-9.]+ or later|is not enabled)/', $body, $r) === 1; + $ok = $ok && (getenv('GPU_EXPECT_REFUSAL') !== '1' || $refused); + + print ' page shows: ' . ($refused ? $r[0] : 'no refusal') . PHP_EOL; + } + + printf("%s %-40s HTTP %d %s\n", $ok ? 'PASS' : 'FAIL', $page, $code, $error); + + $failures += $ok ? 0 : 1; +} + +unlink($jar); + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php new file mode 100644 index 0000000..ec2988a --- /dev/null +++ b/tests/bin/page-permissions.php @@ -0,0 +1,236 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Page permissions and POST-only actions over HTTP (REQ-UI-001 to + * REQ-UI-005). Requests each plugin page as four users: + * + * anonymous not logged in: both pages show the login form + * admin GPU View and GPU Admin: both pages load + * viewer Console and GPU View: inventory loads, nodes is denied, and + * GPUs of a device the viewer may not see are left out + * norealm Console only: both pages are denied + * + * Then shows that tool-reported strings and device descriptions are escaped, + * that a delete or move confirmation sent as GET, or as POST without the + * csrf-magic token, has no effect, and that the same action as a proper POST + * works. Disposable databases only: it resets the admin password and adds + * users and devices. Must parse on PHP 8.0. + * + * GPU_TEST_DATABASE=disposable php plugins/gpu/tests/bin/page-permissions.php http://127.0.0.1:8080/cacti/ + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); + +if (getenv('GPU_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Set GPU_TEST_DATABASE=disposable\n"); + exit(2); +} + +$base = rtrim($argv[1], '/') . '/plugins/gpu/'; +$root = rtrim($argv[1], '/') . '/'; +$password = 'Gpu-' . bin2hex(random_bytes(8)); +$failures = 0; + +$view = (int) db_fetch_cell("SELECT id + 100 FROM plugin_realms WHERE plugin = 'gpu' AND file = 'gpu_inventory.php'"); + +db_execute_prepared("UPDATE user_auth SET password = ?, must_change_password = '', password_change = '', enabled = 'on', locked = '', failed_attempts = 0 WHERE id = 1", array(password_hash($password, PASSWORD_DEFAULT))); + +$users = array(); + +// Realm 8 is Console access. The viewer's policies deny by default (2), so +// only the devices granted to it below are visible, as Cacti's permissive +// model evaluates them; an allow policy with no tree exception is treated by +// core as access to every device. +foreach (array('viewer' => array(8, $view), 'norealm' => array(8)) as $name => $realms) { + $policy = $name === 'viewer' ? 2 : 1; + + db_execute_prepared('DELETE FROM user_auth WHERE username = ?', array($name)); + db_execute_prepared("INSERT INTO user_auth (username, password, realm, full_name, must_change_password, password_change, policy_graphs, policy_trees, policy_hosts, policy_graph_templates, enabled) VALUES (?, ?, 0, ?, '', '', ?, 1, ?, ?, 'on')", array($name, password_hash($password, PASSWORD_DEFAULT), $name, $policy, $policy, $policy)); + $users[$name] = (int) db_fetch_insert_id(); + + foreach ($realms as $realm) { + db_execute_prepared('INSERT INTO user_auth_realm (realm_id, user_id) VALUES (?, ?)', array($realm, $users[$name])); + } +} + +// Two devices with GPU nodes. The viewer is granted only the first one, +// through a device permission (user_auth_perms type 3 under a deny policy). +$devices = array(); +$nodes = array(); + +foreach (array('open' => 'Open node', 'hidden' => 'Hidden node') as $key => $description) { + db_execute_prepared('INSERT INTO host (description, hostname) VALUES (?, ?)', array($description, $key . '.invalid')); + $devices[$key] = (int) db_fetch_insert_id(); + db_execute_prepared("INSERT INTO plugin_gpu_node (host_id, admin_state) VALUES (?, 'enabled')", array($devices[$key])); + $nodes[$key] = (int) db_fetch_insert_id(); +} + +db_execute_prepared('INSERT INTO user_auth_perms (user_id, item_id, type) VALUES (?, ?, 3)', array($users['viewer'], $devices['open'])); + +$open = 'GPU-00000000-0000-4000-8000-0000000000a1'; +$hidden = 'GPU-00000000-0000-4000-8000-0000000000b2'; + +db_execute_prepared("INSERT INTO plugin_gpu_gpu (vendor, uuid, node_id, pci_bus_id, name) VALUES ('nvidia', ?, ?, '00000000:3B:00.0', ?)", array($open, $nodes['open'], '')); +db_execute_prepared("INSERT INTO plugin_gpu_gpu (vendor, uuid, node_id, pci_bus_id, name, pending_node_id, pending_since) VALUES ('nvidia', ?, ?, '00000000:3C:00.0', 'Hidden GPU', ?, 1)", array($hidden, $nodes['hidden'], $nodes['open'])); +$moving = (int) db_fetch_insert_id(); + +function perm_expect($ok, $message) { + global $failures; + + print ($ok ? 'PASS ' : 'FAIL ') . $message . PHP_EOL; + $failures += $ok ? 0 : 1; +} + +function perm_http($url, $jar, $post = null) { + $ch = curl_init($url); + + curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEJAR => $jar, CURLOPT_COOKIEFILE => $jar, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 60)); + + if ($post !== null) { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); + } + + $body = (string) curl_exec($ch); + + return array((int) curl_getinfo($ch, CURLINFO_HTTP_CODE), $body); +} + +function perm_token($body) { + return preg_match('/csrfMagicToken\s*=\s*"([^"]+)"/', $body, $m) ? $m[1] : ''; +} + +function perm_login($user) { + global $root, $password; + + $jar = tempnam(sys_get_temp_dir(), 'gpuperm'); + + if ($user === 'anonymous') { + return $jar; + } + + list(, $login) = perm_http($root . 'index.php', $jar); + perm_http($root . 'index.php', $jar, array('__csrf_magic' => perm_token($login), 'action' => 'login', 'login_username' => $user, 'login_password' => $password)); + + return $jar; +} + +// Markers that only the rendered plugin page contains. +$pages = array('gpu_nodes.php' => 'Export Records', 'gpu_inventory.php' => 'PCI Bus ID'); +$plans = array( + 'anonymous' => array('gpu_nodes.php' => false, 'gpu_inventory.php' => false), + 'admin' => array('gpu_nodes.php' => true, 'gpu_inventory.php' => true), + 'viewer' => array('gpu_nodes.php' => false, 'gpu_inventory.php' => true), + 'norealm' => array('gpu_nodes.php' => false, 'gpu_inventory.php' => false), +); + +foreach ($plans as $user => $expect) { + $jar = perm_login($user); + + foreach ($expect as $page => $allowed) { + list($code, $body) = perm_http($base . $page, $jar); + $shown = strpos($body, $pages[$page]) !== false; + + perm_expect($shown === $allowed && preg_match('/(Fatal error|Parse error|Warning:|Uncaught)/', $body) !== 1, "$user " . ($allowed ? 'sees' : 'is denied') . " $page (HTTP $code)"); + + if ($user === 'anonymous') { + perm_expect(strpos($body, 'login_username') !== false, "anonymous is sent to the login form from $page"); + } + + if ($page === 'gpu_inventory.php' && $allowed) { + $sees = strpos($body, $hidden) !== false; + perm_expect(strpos($body, $open) !== false && $sees === ($user === 'admin'), "$user " . ($user === 'admin' ? 'sees' : 'does not see') . ' the GPU of a device it ' . ($user === 'admin' ? 'may' : 'may not') . ' view'); + + // Tool-reported names and device descriptions are text. + perm_expect(strpos($body, '') === false && strpos($body, '<img src=x id="gpuname">') !== false, "$user's inventory escapes the GPU name"); + perm_expect(strpos($body, '') === false && strpos($body, '<b id="gpuprobe">') !== false, "$user's inventory escapes the device description"); + } + } + + unlink($jar); +} + +$jar = perm_login('admin'); + +foreach (array('gpu_nodes.php', 'gpu_nodes.php?action=edit&id=' . $nodes['open']) as $page) { + list(, $body) = perm_http($base . $page, $jar); + perm_expect(strpos($body, '') === false && strpos($body, '<b id="gpuprobe">') !== false, "$page escapes the device description"); +} + +$pending = function () use ($moving) { + return (int) db_fetch_cell_prepared('SELECT pending_node_id FROM plugin_gpu_gpu WHERE id = ?', array($moving)); +}; + +perm_http($base . 'gpu_nodes.php?action=confirm_move&id=' . $moving, $jar); +perm_expect($pending() === $nodes['open'], 'a move confirmation sent as GET has no effect'); + +perm_http($base . 'gpu_nodes.php', $jar, array('action' => 'confirm_move', 'id' => $moving)); +perm_expect($pending() === $nodes['open'], 'a move confirmation POST without the csrf-magic token has no effect'); + +list(, $list) = perm_http($base . 'gpu_nodes.php', $jar); +perm_expect(strpos($list, 'GPU Moves Awaiting Confirmation') !== false, 'the pending move is listed for confirmation'); +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => perm_token($list), 'action' => 'confirm_move', 'id' => $moving)); +perm_expect($pending() === 0 && (int) db_fetch_cell_prepared('SELECT node_id FROM plugin_gpu_gpu WHERE id = ?', array($moving)) === $nodes['open'], 'the same confirmation as a POST with the token moves the GPU'); + +// A node with GPU records is refused; an empty one is removed, and its Cacti +// device stays. +db_execute_prepared("INSERT INTO host (description, hostname) VALUES ('Empty node', 'empty.invalid')"); +$emptyDevice = (int) db_fetch_insert_id(); +db_execute_prepared("INSERT INTO plugin_gpu_node (host_id, admin_state) VALUES (?, 'enabled')", array($emptyDevice)); +$empty = (int) db_fetch_insert_id(); + +$exists = function ($id) { + return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_gpu_node WHERE id = ?', array($id)) === 1; +}; + +perm_http($base . 'gpu_nodes.php?action=delete&id=' . $empty, $jar); +perm_expect($exists($empty), 'a delete sent as GET has no effect'); + +list(, $list) = perm_http($base . 'gpu_nodes.php', $jar); +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => perm_token($list), 'action' => 'delete', 'id' => $nodes['open'])); +perm_expect($exists($nodes['open']), 'a node that owns GPU records is not deleted'); + +list(, $list) = perm_http($base . 'gpu_nodes.php', $jar); +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => perm_token($list), 'action' => 'delete', 'id' => $empty)); +perm_expect(!$exists($empty) && (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM host WHERE id = ?', array($emptyDevice)) === 1, 'an empty node is deleted as a POST with the token, and its device stays'); + +// Registering a device through the form, and refusing it a second time. +list(, $form) = perm_http($base . 'gpu_nodes.php?action=edit', $jar); +perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => perm_token($form), 'action' => 'save', 'id' => 0, 'host_id' => $emptyDevice, 'enabled' => 'on')); +perm_expect((int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_gpu_node WHERE host_id = ?', array($emptyDevice)) === 1, 'a device is registered as a node through the form'); + +list(, $again) = perm_http($base . 'gpu_nodes.php', $jar, array('__csrf_magic' => perm_token($form), 'action' => 'save', 'id' => 0, 'host_id' => $emptyDevice, 'enabled' => 'on')); +perm_expect(strpos($again, 'already a GPU node') !== false && (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_gpu_node WHERE host_id = ?', array($emptyDevice)) === 1, 'the same device is refused a second time'); + +// The export is GPU Admin only and holds every record. +list($code, $export) = perm_http($base . 'gpu_nodes.php?action=export', $jar); +$document = json_decode($export, true); +perm_expect($code === 200 && is_array($document) && count($document['gpus']) === 2 && count($document['nodes']) === 3, 'GPU Admin downloads every node and GPU record'); + +unlink($jar); + +$jar = perm_login('viewer'); +list(, $export) = perm_http($base . 'gpu_nodes.php?action=export', $jar); +perm_expect(strpos($export, $open) === false, 'a GPU View user cannot download the export'); +unlink($jar); + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bin/php-guard-check.php b/tests/bin/php-guard-check.php new file mode 100644 index 0000000..d9ed4b2 --- /dev/null +++ b/tests/bin/php-guard-check.php @@ -0,0 +1,125 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Proves the PHP 8.2 guard against a real Cacti install, on whatever PHP runs + * this script. Run from the Cacti root as the poller user: + * + * php plugins/gpu/tests/bin/php-guard-check.php + * + * Below 8.2 it expects install and enable to be refused with a message, no + * tables, hooks, or realms, no plugin class loaded, and every hook shim to + * return quietly even when hooks were registered by an earlier, supported + * PHP. On 8.2 and later it expects install and enable to succeed. + * + * This file must itself parse on PHP 8.0. Exits non-zero on any failure. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/plugins.php'); +require_once($config['base_path'] . '/lib/poller.php'); + +$failures = 0; + +function guard_expect($condition, $message) { + global $failures; + + print ($condition ? 'PASS ' : 'FAIL ') . $message . PHP_EOL; + + if (!$condition) { + $failures++; + } +} + +function guard_state() { + return array( + 'status' => db_fetch_cell("SELECT status FROM plugin_config WHERE directory = 'gpu'"), + 'hooks' => (int) db_fetch_cell("SELECT COUNT(*) FROM plugin_hooks WHERE name = 'gpu'"), + 'realms' => (int) db_fetch_cell("SELECT COUNT(*) FROM plugin_realms WHERE plugin = 'gpu'"), + 'tables' => (int) db_fetch_cell("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'plugin\\_gpu\\_%'"), + ); +} + +/* + * Every hook callback setup.php defines, called as Cacti would. Listed by + * name so that this file needs no plugin class to enumerate them. + */ +function guard_call_shims() { + $nav = array('index.php:' => array('title' => 'Console')); + + foreach (array('gpu_config_arrays', 'gpu_config_settings') as $function) { + if (function_exists($function)) { + $function(); + } + } + + if (function_exists('gpu_draw_navigation_text')) { + guard_expect(gpu_draw_navigation_text($nav) === $nav, 'draw_navigation_text returns the navigation unchanged'); + } + + // Core's own dispatch, as every page load does. + api_plugin_hook('config_arrays'); + api_plugin_hook('config_settings'); + api_plugin_hook('poller_bottom'); + // Core's own entries (plugins.php) are added by the dispatch; none of ours may be. + $dispatched = api_plugin_hook_function('draw_navigation_text', $nav); + guard_expect(is_array($dispatched) && preg_grep('/^gpu/', array_keys($dispatched)) === array(), 'core dispatch of draw_navigation_text adds no gpu entry'); +} + +$supported = version_compare(PHP_VERSION, '8.2.0', '>='); +$preexisting = guard_state(); + +print 'PHP ' . PHP_VERSION . ', Cacti ' . CACTI_VERSION . ', status ' . var_export($preexisting['status'], true) . ', hooks already registered: ' . $preexisting['hooks'] . PHP_EOL; + +if (!$supported && ($preexisting['status'] == 1 || $preexisting['hooks'] > 0)) { + // Enabled under a supported PHP, then PHP was downgraded. Cacti + // still calls the shims; each must return before loading any class. + include_once($config['base_path'] . '/plugins/gpu/setup.php'); + + guard_call_shims(); + guard_expect(plugin_gpu_check_config() === false, 'check_config refuses'); + guard_expect(!class_exists('Somethingwithproof\\Gpu\\Log', false), 'no plugin class was loaded'); + guard_expect(guard_state()['tables'] === $preexisting['tables'], 'plugin tables were not touched'); +} else { + ob_start(); + api_plugin_install('gpu'); + api_plugin_enable('gpu'); + ob_end_clean(); + + $state = guard_state(); + + if ($supported) { + guard_expect($state['status'] == 1, 'install and enable succeed (status ' . $state['status'] . ')'); + guard_expect($state['tables'] === 2, 'both plugin tables exist (' . $state['tables'] . ')'); + guard_expect($state['hooks'] === 3 && $state['realms'] === 2, 'hooks and realms are registered'); + } else { + guard_expect($state['status'] == 2, 'plugin is left as needing configuration, not enabled (status ' . $state['status'] . ')'); + guard_expect($state['tables'] === 0 && $state['hooks'] === 0 && $state['realms'] === 0, 'no tables, hooks, or realms were created'); + guard_expect(!class_exists('Somethingwithproof\\Gpu\\Log', false), 'no plugin class was loaded'); + + $logged = (int) shell_exec('grep -c ' . escapeshellarg('GPU ERROR: The GPU plugin requires PHP 8.2.0 or later') . ' ' . escapeshellarg(cacti_log_file())); + guard_expect($logged > 0, 'the refusal naming PHP 8.2.0 was logged'); + + guard_call_shims(); + } +} + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bootstrap-integration.php b/tests/bootstrap-integration.php new file mode 100644 index 0000000..e4c7aec --- /dev/null +++ b/tests/bootstrap-integration.php @@ -0,0 +1,67 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_gpu, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_gpu + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Integration bootstrap. The tests drive Cacti in separate PHP processes, as + * plugins.php and the CLI tools do, so nothing from Cacti is loaded here. + */ + +$cacti = rtrim((string) getenv('CACTI_PATH'), '/'); + +if ($cacti === '' || !is_file($cacti . '/include/config.php') || !is_dir($cacti . '/plugins/gpu')) { + fwrite(STDERR, "Set CACTI_PATH to an installed Cacti with this plugin at plugins/gpu.\n"); + exit(2); +} + +if (getenv('GPU_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Set GPU_TEST_DATABASE=disposable: these tests install and uninstall the plugin.\n"); + exit(2); +} + +/** + * Run tests/bin/lifecycle.php in a fresh PHP process and decode its state. + * + * @return array + */ +function lifecycle(string $action, string $argument = ''): array { + $cacti = rtrim((string) getenv('CACTI_PATH'), '/'); + $command = [PHP_BINARY, $cacti . '/plugins/gpu/tests/bin/lifecycle.php', $action]; + + if ($argument !== '') { + $command[] = $argument; + } + + $process = proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, $cacti); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + + fclose($pipes[1]); + fclose($pipes[2]); + + $status = proc_close($process); + $state = json_decode((string) $stdout, true); + + if ($status !== 0 || !is_array($state)) { + throw new RuntimeException("lifecycle.php $action failed ($status): $stderr $stdout"); + } + + $state['stderr'] = $stderr; + + return $state; +} From 3dba545461a8daff0fe567e8c48e47bdf40c9d54 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 00:20:12 -0800 Subject: [PATCH 06/10] ci: test matrix, PHP 8.1 refusal, static analysis, and REUSE Add the CI workflow, ported from plugin_cloud's foundation: - PHP 8.0 lint of setup.php, include/, the page scripts, and the test entry scripts. - PHP 8.2, 8.3, 8.4, and 8.5 against Cacti release/1.2.31 and the 1.2.x branch with MariaDB 11.8: the unit suite, the lifecycle suite, install and enable, the POT check, a poller run, page permissions, and a clean Cacti log. PHPStan level 9 at phpVersion 8.2 runs against 1.2.31. - A PHP 8.1 job on Cacti 1.2.31 that expects the refusal, then install on 8.2, then quiet hooks, a working poller, and loading core pages back on 8.1. - actionlint and zizmor on the workflows, and REUSE lint. Pest comes from Cacti's locked plugin harness at the revision maintained plugins pin. This is the provisional harness choice; #12 stays open. `ci-ok` is the single required check. Refs #34 Signed-off-by: Thomas Vincent --- .github/workflows/plugin-ci-workflow.yml | 418 +++++++++++++++++++++++ tests/lint-workflows.sh | 48 +++ 2 files changed, 466 insertions(+) create mode 100644 .github/workflows/plugin-ci-workflow.yml create mode 100644 tests/lint-workflows.sh diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml new file mode 100644 index 0000000..24edb04 --- /dev/null +++ b/.github/workflows/plugin-ci-workflow.yml @@ -0,0 +1,418 @@ +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_gpu, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_gpu +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. + +# Follows plugin_smokeping and the maintained plugins (servcheck, webseer, +# monitor): Cacti checked out with this plugin under plugins/, a MariaDB +# service, Cacti installed from its CLI, the plugin installed with +# plugin_manage.php, and Pest from the locked shared plugin harness. The test +# harness choice is pending maintainers in #12; this provisional choice +# matches what maintained plugins use today. +# +# `ci-ok` is the one check branch protection needs to name. + +name: CI + +on: + push: + branches: + - main + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + # Cacti includes setup.php on whatever PHP a 1.2.31 site runs, so the entry + # points must parse on PHP 8.0 even though the plugin refuses to run below + # 8.2. + entry-point-lint: + name: PHP 8.0 entry point lint + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install PHP 8.0 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.0' + coverage: none + + - name: Lint entry points + run: | + set -euo pipefail + php -v + for f in *.php include/*.php locales/*.php tests/bin/*.php; do + php -l "$f" + done + + integration-test: + name: PHP ${{ matrix.php }} on Cacti ${{ matrix.cacti }} + runs-on: ubuntu-latest + timeout-minutes: 30 + + strategy: + fail-fast: false + matrix: + php: ['8.2', '8.3', '8.4', '8.5'] + cacti: ['release/1.2.31', '1.2.x'] + + services: + mariadb: + image: mariadb:11.8@sha256:6422478cb8e159f080fb1d8ccf65101e26fe51385787fde7d16c3b165a331f15 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mariadb-admin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + steps: + - name: Checkout Cacti + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/cacti + ref: ${{ matrix.cacti }} + path: cacti + + - name: Checkout GPU plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: cacti/plugins/gpu + + - name: Install PHP ${{ matrix.php }} + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ matrix.php }} + tools: composer:2.10.3, phpstan:2.3.5 + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "post_max_size=256M, max_execution_time=60, date.timezone=America/New_York" + coverage: none + + - name: Install system dependencies + run: | + sudo apt-get update + # Ubuntu 26.04's mysql client rejects the DELIMITER line at the top of + # Cacti's cacti.sql; MariaDB's client loads it. + sudo apt-get install -y rrdtool gettext mariadb-client + + # Core's release archives exclude tests/, so fetch the shared harness lock + # at the same immutable revision the maintained plugins pin. + - name: Checkout shared CI tooling + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: Cacti/cacti + ref: f3ff777992875740e4665fedfe2eff8335f5b894 + persist-credentials: false + path: ci-tools + sparse-checkout: | + tests/tools/plugin-harness + + - name: Install the locked Pest harness + run: | + set -euo pipefail + harness="$RUNNER_TEMP/cacti-plugin-harness" + mkdir -p "$harness" + cp ci-tools/tests/tools/plugin-harness/composer.json ci-tools/tests/tools/plugin-harness/composer.lock "$harness/" + composer --working-dir="$harness" validate --strict + composer --working-dir="$harness" install --no-interaction --no-progress --prefer-dist + echo "CACTI_PEST_BIN=$harness/vendor/bin/pest" >> "$GITHUB_ENV" + + - name: Initialize Cacti database + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + chmod 600 ~/.my.cnf + mariadb -e "CREATE USER IF NOT EXISTS 'cactiuser'@'127.0.0.1' IDENTIFIED BY 'cactiuser';" + mariadb -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'127.0.0.1';" + mariadb -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'127.0.0.1';" + mariadb -e "FLUSH PRIVILEGES;" + mariadb cacti < cacti/cacti.sql + mariadb -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '$(command -v php)')" cacti + + - name: Create Cacti config.php + run: | + sed -r "s/localhost/127.0.0.1/g" cacti/include/config.php.dist > cacti/include/config.php + + - name: Install Cacti via CLI + working-directory: cacti + run: php cli/install_cacti.php --accept-eula --install --force + + - name: Run unit tests + working-directory: cacti/plugins/gpu + run: '"$CACTI_PEST_BIN" --configuration=phpunit.xml' + + # Installs, upgrades, and uninstalls the plugin through Cacti's own + # plugin API, so it runs before the plugin is installed for the poller. + - name: Run lifecycle integration tests + working-directory: cacti/plugins/gpu + env: + CACTI_PATH: ${{ github.workspace }}/cacti + GPU_TEST_DATABASE: disposable + run: '"$CACTI_PEST_BIN" --configuration=phpunit-integration.xml' + + # The integration tests provoke refusals that the plugin logs as errors, + # such as a schema downgrade. Keep their log apart so the error check + # below covers the install and the poller run. + - name: Set the integration tests' log aside + if: always() + run: | + if [ -f cacti/log/cacti.log ]; then + mv cacti/log/cacti.log cacti/log/integration.log + fi + + - name: Install and enable the plugin + working-directory: cacti + run: php plugins/gpu/tests/bin/php-guard-check.php + + # Against the minimum supported release only: the 1.2.x branch's + # docblocks give PDO connections as resources and mistype some + # parameters, which PHPStan reports at every call site. + - name: Run PHPStan + if: matrix.cacti == 'release/1.2.31' + working-directory: cacti/plugins/gpu + env: + CACTI_PATH: ${{ github.workspace }}/cacti + run: phpstan analyse -c phpstan.neon --no-progress + + - name: Verify translation template and catalogs + working-directory: cacti/plugins/gpu + run: sh locales/build_gettext.sh --check + + - name: Run Cacti poller + working-directory: cacti + run: | + php poller.php --poller=1 --force --debug + grep -q "SYSTEM STATS" log/cacti.log + + - name: Check page permissions and POST-only actions + working-directory: cacti + env: + GPU_TEST_DATABASE: disposable + run: | + php -S 127.0.0.1:8080 -t "$GITHUB_WORKSPACE" > "$RUNNER_TEMP/php-server.log" 2>&1 & + for _ in 1 2 3 4 5 6 7 8 9 10; do + curl -fsS -o /dev/null http://127.0.0.1:8080/cacti/index.php && break + sleep 1 + done + php plugins/gpu/tests/bin/page-permissions.php http://127.0.0.1:8080/cacti/ + if grep -E "Fatal error|Warning:|Uncaught" "$RUNNER_TEMP/php-server.log"; then + exit 1 + fi + + - name: Check Cacti log for errors + if: always() + run: | + if [ -f cacti/log/integration.log ]; then + echo "== integration tests (not checked)" + cat cacti/log/integration.log + fi + if [ -f cacti/log/cacti.log ]; then + echo "== install and poller run" + cat cacti/log/cacti.log + if grep -E "FATAL:|ERROR:|WARNING:" cacti/log/cacti.log; then + exit 1 + fi + fi + + # A 1.2.31 site may still run PHP 8.1. Enabling the plugin there must be + # refused with a message and leave Cacti working, both on a fresh install + # and after an upgrade-in-place left the plugin's hooks registered. + php-guard: + name: Refusal on PHP 8.1 with Cacti 1.2.31 + runs-on: ubuntu-latest + timeout-minutes: 20 + + services: + mariadb: + image: mariadb:11.8@sha256:6422478cb8e159f080fb1d8ccf65101e26fe51385787fde7d16c3b165a331f15 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mariadb-admin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + steps: + - name: Checkout Cacti + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/cacti + ref: release/1.2.31 + path: cacti + + - name: Checkout GPU plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: cacti/plugins/gpu + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y rrdtool mariadb-client + + - name: Install PHP 8.1 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.1' + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "date.timezone=America/New_York" + coverage: none + + - name: Initialize Cacti database + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + chmod 600 ~/.my.cnf + mariadb -e "CREATE USER IF NOT EXISTS 'cactiuser'@'127.0.0.1' IDENTIFIED BY 'cactiuser';" + mariadb -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'127.0.0.1';" + mariadb -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'127.0.0.1';" + mariadb -e "FLUSH PRIVILEGES;" + mariadb cacti < cacti/cacti.sql + sed -r "s/localhost/127.0.0.1/g" cacti/include/config.php.dist > cacti/include/config.php + + - name: Install Cacti via CLI + working-directory: cacti + run: php cli/install_cacti.php --accept-eula --install --force + + - name: Install is refused on PHP 8.1 + working-directory: cacti + run: php plugins/gpu/tests/bin/php-guard-check.php + + - name: Install PHP 8.2 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.2' + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "date.timezone=America/New_York" + coverage: none + + - name: Install succeeds on PHP 8.2 + working-directory: cacti + run: php plugins/gpu/tests/bin/php-guard-check.php + + - name: Install PHP 8.1 again + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.1' + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "date.timezone=America/New_York" + coverage: none + + - name: Registered hooks stay quiet on PHP 8.1 + working-directory: cacti + run: php plugins/gpu/tests/bin/php-guard-check.php + + # The poller dispatches poller_bottom and loads every enabled plugin's + # setup.php, as each page does through include/global.php. + - name: Cacti's poller still runs on PHP 8.1 + working-directory: cacti + run: | + php poller.php --poller=1 --force --debug + grep -q "SYSTEM STATS" log/cacti.log + + # Every page includes each enabled plugin's setup.php and runs its + # hooks, so the core pages must keep loading, and the plugin's own pages + # must show the refusal instead of failing. + - name: Core pages still load on PHP 8.1 + working-directory: cacti + env: + GPU_TEST_DATABASE: disposable + GPU_EXPECT_REFUSAL: '1' + run: | + php -S 127.0.0.1:8080 -t "$GITHUB_WORKSPACE" > "$RUNNER_TEMP/php-server.log" 2>&1 & + for _ in 1 2 3 4 5 6 7 8 9 10; do + curl -fsS -o /dev/null http://127.0.0.1:8080/cacti/index.php && break + sleep 1 + done + php plugins/gpu/tests/bin/page-check.php http://127.0.0.1:8080/cacti/ \ + index.php host.php graph_view.php graphs.php data_sources.php plugins.php \ + settings.php utilities.php user_admin.php \ + plugins/gpu/gpu_inventory.php plugins/gpu/gpu_nodes.php + if grep -E "Fatal error|Parse error|Uncaught" "$RUNNER_TEMP/php-server.log"; then + exit 1 + fi + + workflow-lint: + name: Workflow lint + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Lint the workflows with actionlint and zizmor + env: + GH_TOKEN: ${{ github.token }} + run: sh tests/lint-workflows.sh + + reuse: + name: REUSE compliance + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Lint licensing metadata + run: pipx run --spec 'reuse[charset-normalizer]==6.3.0' reuse lint + + ci-ok: + name: ci-ok + if: ${{ always() }} + needs: + - entry-point-lint + - integration-test + - php-guard + - workflow-lint + - reuse + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: {} + steps: + - name: Require every job to have succeeded + env: + NEEDS: ${{ toJSON(needs) }} + run: | + set -euo pipefail + echo "$NEEDS" | jq -r 'to_entries[] | "\(.key): \(.value.result)"' + echo "$NEEDS" | jq -e 'all(.[]; .result == "success")' >/dev/null diff --git a/tests/lint-workflows.sh b/tests/lint-workflows.sh new file mode 100644 index 0000000..6158355 --- /dev/null +++ b/tests/lint-workflows.sh @@ -0,0 +1,48 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_gpu, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_gpu +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. + +# Lint the GitHub Actions workflows with actionlint (syntax, expressions, +# ShellCheck on run: steps) and zizmor (security: script injection, excessive +# permissions, unpinned actions, credential persistence). CI and a developer +# machine run this same file, so the pinned tool versions live only here. +# +# sh tests/lint-workflows.sh +# +# Needs Docker. zizmor's online audits (impostor commits, known-vulnerable +# actions) run when GH_TOKEN is set in the environment and are skipped, with a +# note, when it is not. Exits non-zero on any finding. +set -eu + +ACTIONLINT=rhysd/actionlint:1.7.12@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667 +ZIZMOR=ghcr.io/zizmorcore/zizmor:1.32.0@sha256:3014cc8f68f663935f69b3c3e0e41f5ce102b268d97db13db0f62208747f860d + +PLUGIN=$(cd "$(dirname "$0")/.." && pwd) +status=0 + +echo "== actionlint" +docker run --rm -v "$PLUGIN":/repo:ro -w /repo "$ACTIONLINT" -color || status=1 + +echo "== zizmor" +if [ -n "${GH_TOKEN:-}" ]; then + # The token goes in by name, so its value is never on a command line. + docker run --rm -e GH_TOKEN -v "$PLUGIN":/repo:ro -w /repo "$ZIZMOR" --no-progress --color=always .github || status=1 +else + echo "GH_TOKEN is not set: running zizmor's offline audits only" + docker run --rm -v "$PLUGIN":/repo:ro -w /repo "$ZIZMOR" --offline --no-progress --color=always .github || status=1 +fi + +exit $status From 6f759e013010f25c5cfefe22a5790110481314ee Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 00:21:19 -0800 Subject: [PATCH 07/10] docs: describe what milestone 2 ships and where it differs from the plan The README status moves from proposal to milestone 2 and lists what the foundation does, with evaluation install steps, and says plainly that nothing is collected until milestone 3. The plan records where the implementation diverges: the provisional Somethingwithproof\Gpu namespace, the M2 capability set, the settled class names, the replacement flag matching on bus ID regardless of index, refusal of MIG UUIDs and of malformed or duplicate output, NVIDIA only until #19, pending moves, presence as two states plus a replacement flag, uninstall questions as settings with an export on the GPU Nodes page, and the provisional Pest harness with synthetic identity fixtures. Refs #29, #30, #31, #32, #33, #34 Signed-off-by: Thomas Vincent --- README.md | 19 ++++++++++++++++++- docs/PLAN.md | 25 +++++++++++++------------ 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 4e1e343..0fd1336 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A proposed Cacti 1.2 plugin that brings per-GPU utilization, memory, temperature, power, ECC errors, XID errors, and throttling reasons from NVIDIA and AMD tools into Cacti. Each GPU becomes an index of a data query on its node's device, so GPU graphs sit next to the node's other graphs under Cacti's permissions, and Thold and Maint can alert on and suppress them. -> **Status: proposal.** This repository contains no plugin code yet. It holds the design, its decision records, and the requirements tracked as issues and milestones. Nothing below describes shipped behavior. +> **Status: milestone 2 (foundation).** The plugin installs, registers GPU nodes, and keeps GPU identity records, but it collects nothing: no vendor tool is run and no graph is created until milestone 3. Do not run it in production. Everything below the milestone 2 section describes the plan, not shipped behavior. ## Why @@ -21,6 +21,23 @@ The plugin closes that gap by turning vendor tool output into Cacti data sources Out of scope: any command that changes a GPU or node (clocks, power limits, resets, MIG layout), a plugin-owned alerting engine, a custom daemon or network protocol, and scheduler or job accounting. See the plan for the research backlog. +## What milestone 2 ships + +- **A guarded install.** On PHP below 8.2, install and enable are refused with a message naming the required version, and the rest of Cacti keeps working. `setup.php` and the page scripts parse on PHP 8.0. +- **Lifecycle.** Install, upgrade, disable, and uninstall through Cacti's Plugins page. Upgrades are ordered, finish after an interruption, and change the recorded version only after they succeed. Uninstall keeps the plugin's tables unless you clear *Keep Plugin Tables on Uninstall*; it never touches a Cacti device, data source, graph, or RRD file. +- **Two realms.** *GPU Admin* opens **GPU Nodes**, where you register Cacti devices as GPU nodes, confirm or reject GPU moves between nodes, and export every record as JSON. *GPU View* opens **GPU Inventory**, which lists GPUs only on devices the viewer may see. Both pages are under Management, and every change is a POST checked by csrf-magic. +- **GPU identity records.** Each GPU is keyed by vendor and UUID. Index, PCI bus ID, name, driver, and the reporting tool are attributes that change in place. A new UUID in a known slot is flagged as a possible replacement and starts its own history; a GPU seen at another node moves only when an operator confirms; a GPU missing from successful collections is marked absent after a configurable count and never deleted. Only NVIDIA whole-GPU UUIDs are accepted for now; MIG instances wait on decision #13, and AMD on research #19. The rules are exercised by fixture sequences, since no collector feeds them yet. +- **Tests and CI.** Unit and source-rule suites with no GPU or database, lifecycle and page-permission checks against Cacti 1.2.31 and current 1.2.x on PHP 8.2 to 8.5, a PHP 8.1 refusal job, a PHP 8.0 lint of the entry points, PHPStan at level 9, and REUSE. The harness is provisional until #12 is decided. + +### Install for evaluation + +These steps install the milestone 2 code to try it. They require Cacti 1.2.31 or later on PHP 8.2 or later. + +1. Copy the repository to `plugins/gpu` under your Cacti directory. The directory must be named `gpu`. +2. In Cacti, open **Configuration > Plugins**, then install and enable **GPU**. +3. Give users the *GPU View* or *GPU Admin* realm under **Configuration > Users**. The installing user gets both. +4. Optionally adjust **Configuration > Settings > GPU**: *Mark Absent After* (default 3 successful collections, from 1 to 100) and *Keep Plugin Tables on Uninstall* (default on). + ## Open question: how metrics reach Cacti The largest undecided choice is the collection path: a Cacti poller on the GPU node, SNMP `extend`, scraping `dcgm-exporter`, or something else. Each puts the trust boundary in a different place. It is tracked as decision [#7](https://github.com/somethingwithproof/plugin_gpu/issues/7) and gated on measurements in milestone 1. The plan describes the options under [Collection paths](docs/PLAN.md#collection-paths). diff --git a/docs/PLAN.md b/docs/PLAN.md index f16c946..0dbbb19 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,6 +1,6 @@ # Cacti 1.2 GPU Plugin Plan -Status: proposal, revision 2 (2026-11-15). Revision 2 folds in the milestone 1 documentation and source research in [`docs/research/`](research/); items that need hardware are marked *live* and listed in each research page's Live checks table. Nothing described here as a plugin capability exists yet. Statements about vendor tools, Cacti core, Thold, and net-snmp describe upstream behavior and cite the source that was checked, with the version or commit where one was available. Statements that could not be verified are listed as assumptions with the research issue that confirms them; they are not facts. Owner and estimates are not assigned; milestone 1 produces the estimates. +Status: proposal, revision 2 (2026-11-15). Revision 2 folds in the milestone 1 documentation and source research in [`docs/research/`](research/); items that need hardware are marked *live* and listed in each research page's Live checks table. Milestone 2 (foundation) is implemented: the PHP guard, lifecycle, realms and pages, node registry, GPU identity records, and the test harness. Where it differs from the text below, the difference is stated in place. Nothing that collects from a GPU exists yet. Statements about vendor tools, Cacti core, Thold, and net-snmp describe upstream behavior and cite the source that was checked, with the version or commit where one was available. Statements that could not be verified are listed as assumptions with the research issue that confirms them; they are not facts. Owner and estimates are not assigned; milestone 1 produces the estimates. `plugin_gpu` brings per-GPU utilization, memory, temperature, power, ECC errors, XID errors, and clock throttling reasons from NVIDIA and AMD tools into Cacti 1.2. Each GPU becomes an index of a data query on its node's Cacti device, so operators see GPU graphs next to the node's other graphs, under Cacti's own permissions, and alert on them with Thold and Maint. @@ -68,7 +68,7 @@ Code loaded after the check may use PHP features through 8.2 where they make the **Vendor tools.** The supported driver, DCGM, and ROCm lines are not chosen yet. [research/compatibility-matrix.md](research/compatibility-matrix.md) lists the vendor-supported lines (NVIDIA R580, R595, R620; ROCm 10.1.0 as the current release) and proposes a support set for the owner to confirm; fixture and pilot hardware are *live*. The DCGM field IDs the plan uses were compared at two tags: `v3.3.9` and `v4.7.0`. -**Plugin metadata.** `INFO` will declare `compat = 1.2.31`. The capability set is set in M2 and M6. For phase 3 it includes `remote_collect:1` (for `poller_output` and the script server input) and `remote_poller:1`, because `poller_bottom`, where the collector runs, is gated by `remote_poller` on a remote collector. The author, copyright holder, and contact in `INFO` and file headers are Thomas Vincent, and the homepage is this repository. +**Plugin metadata.** `INFO` declares `compat = 1.2.31`. The capability set is set in M2 and M6; M2 declares only `online_view:1, online_mgmt:1`, because nothing is collected yet. For phase 3 it includes `remote_collect:1` (for `poller_output` and the script server input) and `remote_poller:1`, because `poller_bottom`, where the collector runs, is gated by `remote_poller` on a remote collector. The author, copyright holder, and contact in `INFO` and file headers are Thomas Vincent, and the homepage is this repository. ## Upstream behavior the design depends on @@ -227,10 +227,11 @@ Cacti keeps history by data query index. An index that changes meaning attaches Rules, tested by fixtures (REQ-ID-001 to 006): -- A new UUID at a known node, index, and bus ID creates a new GPU record flagged as a possible replacement. It never inherits history. +- A new UUID at a known node, index, and bus ID creates a new GPU record flagged as a possible replacement. It never inherits history. As built in M2, the flag is raised when the bus ID of an unreported record at the same node matches, whatever the index, because the index can change at any boot; this flags every case the rule names and some it does not. - A UUID seen at a different node is recorded as moved only when an operator confirms. - A GPU missing from collection is marked absent after N consecutive successful collections, never deleted automatically, and keeps its index, data sources, and RRD files. - A failed collection, a tool error, or an empty result never marks GPUs absent. +- As built in M2: a collection whose rows fail validation, or that reports one UUID or one PCI bus ID twice, is refused whole and treated as failed. MIG instance UUIDs (`MIG-...`) are refused as identity keys until decision #13, because a recreated instance's UUID reuse is unresolved ([research/mig.md](research/mig.md)). Only NVIDIA identities are accepted until #19 settles AMD UUID stability. A GPU seen at another node keeps its record and node, with the other node stored as a pending move that GPU Admin confirms or rejects. A node that owns GPU records cannot be deleted, only disabled. ## Cacti objects @@ -288,7 +289,7 @@ ECC and retired-page values are numbers the GPU reports. XID is different: the k |---|---|---| | Freshness | Current, delayed, stale, never observed | Observation time against the expected interval | | Execution | Completed, tool error, permission denied, timed out, unknown | Exit status, timeout, and output validation | -| GPU presence | Present, absent, possible replacement | Inventory records | +| GPU presence | Present, absent; possible replacement is a separate flag, since a replacement card is itself present (M2) | Inventory records | | Maintenance | In maintenance, not in maintenance | Maint's `plugin_maint_check_cacti_host()` for the node's device (guarded call; the `is_device_in_maintenance` hook has no caller in core) | Each cached observation carries observation time, ingestion time, expected interval, backend, and tool version. A recent page refresh never counts as a recent measurement. @@ -337,28 +338,28 @@ Plugin code is object-oriented wherever Cacti's plugin contract allows it. Cacti **Layout.** -- Classes live in `lib/*.php` under the `Cacti\Gpu` namespace, one class per file, loaded by a small `spl_autoload_register()` loader registered only after the PHP version check. No Composer runtime dependency. Files stay at depth 2 or less because the gettext build and the POT check scan with `find . -maxdepth 2`. +- Classes live in `lib/*.php` under the `Somethingwithproof\Gpu` namespace (provisional until the repository home and name are decided in #11; `Cacti\Gpu` if the plugin moves to the Cacti organization), one class per file, loaded by a small `spl_autoload_register()` loader registered only after the PHP version check. No Composer runtime dependency. Files stay at depth 2 or less because the gettext build and the POT check scan with `find . -maxdepth 2`. - Settings use the `config_settings` hook. Logging uses `cacti_log()` with a `GPU` tag. Forms rely on csrf-magic. - Strings use the `gpu` text domain with a `locales/` directory and a POT file. - Realms: "GPU View" and "GPU Admin", each a list of page files. -**Planned classes.** Names are illustrative; milestone 2 settles the set. +**Classes.** Milestone 2 settled the first set; the rest of the table is planned. | Kind | Examples | Notes | |---|---|---| -| Value objects | `Node`, `Gpu`, `GpuIdentity`, `Observation` | `readonly` classes built by named constructors | -| Enums | `Freshness`, `ExecutionState`, `Presence`, `Vendor` | String-backed; stored as `varchar` | -| Repositories | `NodeRepository`, `GpuRepository`, `ObservationRepository` | Only classes that issue SQL, always prepared, with an explicit connection | +| Value objects | `Node`, `GpuReport`, `GpuSnapshot`, `GpuRecord`, `Reconciliation` (M2); `Observation` (planned) | `readonly` classes built by named constructors | +| Enums | `Presence`, `Vendor`, `AdminState` (M2); `Freshness`, `ExecutionState` (planned) | String-backed; stored as `varchar` | +| Repositories | `NodeRepository`, `GpuRepository`, `SettingsRepository`, `Schema` (M2); `ObservationRepository` (planned) | Only classes that issue SQL, always prepared, with an explicit connection | | Backends | `NvidiaSmiBackend`, `DcgmBackend`, `AmdSmiBackend` | Behind one interface; tested against captured output fixtures | | Process | `CommandRunner` | Fixed argument vectors, timeout, output cap, no shell | -| Services | `InventoryService`, `FreshnessEvaluator`, `ThrottleDecoder` | Return decisions as objects; a runner applies side effects | +| Services | `IdentityReconciler` and `Inventory` (M2); `FreshnessEvaluator`, `ThrottleDecoder` (planned) | Return decisions as objects; a runner applies side effects | | Infrastructure | `Clock` with system and fixed implementations | Injected wherever time matters | ## Storage, jobs, upgrades, and recovery Plugin tables hold node mappings, GPU records, the observation cache, and health. They are created and upgraded with Cacti's tracked plugin table API, and the stored plugin version changes only after a migration succeeds. The collector runs from `poller_bottom` through `exec_background()` as one `register_process_start()` process per poller, with a time budget. Runs are idempotent. -Disabling the plugin stops jobs and leaves devices, graphs, and RRD files untouched. Uninstalling offers an export, then asks separately whether to drop plugin tables and whether to remove plugin-created Cacti objects. The plugin never changes anything on a GPU node. Backup documentation covers the Cacti database and the RRD directory. A restore must not attach an RRD file to a different UUID, which is a release test. +Disabling the plugin stops jobs and leaves devices, graphs, and RRD files untouched. Uninstalling offers an export, then asks separately whether to drop plugin tables and whether to remove plugin-created Cacti objects. Cacti 1.2 gives a plugin no prompt during uninstall, so as built in M2 the questions are settings answered before uninstalling: *Keep Plugin Tables on Uninstall* (default on), with the export on the GPU Nodes page. M2 creates no Cacti objects, so the second question arrives with the milestone that creates them. The plugin never changes anything on a GPU node. Backup documentation covers the Cacti database and the RRD directory. A restore must not attach an RRD file to a different UUID, which is a release test. ## Performance @@ -407,7 +408,7 @@ Phase 2 needs a security review of the DCGM and amd-smi invocation paths and any - **Alerting.** Thold fires and recovers on fixture throttle, ECC, and staleness; Maint suppresses it. - **Remote.** Collector offline, recovery mode, replication after reconnect. - **Failure scenarios before each phase release:** tool missing, timeout, permission denied, driver unloaded, GPU lost mid-collection, node unreachable, clock skew, full disk, interrupted collector, duplicate collector start, interrupted upgrade. -- **Harness.** Use the harness maintained Cacti plugins use, and confirm with maintainers before adding test or CI infrastructure (#12). +- **Harness.** Use the harness maintained Cacti plugins use, and confirm with maintainers before adding test or CI infrastructure (#12). M2 adopts it provisionally: Pest from the locked plugin harness in Cacti's `tests/tools/plugin-harness`, as maintained plugins run it, until #12 is decided. Identity fixtures in M2 are synthetic sequences, not captured tool output; captured fixtures arrive with the first backend. ## Milestones From 4db5168b9571d38f7b21de6be19a1036deffee71 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 00:49:01 -0800 Subject: [PATCH 08/10] fix: guard identity writes, GPU record reads, export, and node edits Address four review findings on the M2 foundation: - Write a reconciled update only while the record still has the node and pending node it was read with. An operator who confirms or rejects a move between the read and the write now wins; the stale update matches no row and the next collection recomputes. The reconciliation carries each record as read, and an update without that read state is not written. - Report a failed read of the stored GPU records instead of treating it as no records. The collection is then not recorded and a warning is logged, so a replacement link is not lost. - Encode the JSON export with JSON_HEX_TAG. csrf-magic appends a script to any response holding " --- gpu_nodes.php | 7 ++++- lib/GpuRepository.php | 37 +++++++++++++++++++--- lib/IdentityReconciler.php | 8 ++++- lib/Inventory.php | 10 +++++- lib/InventoryExport.php | 5 ++- lib/NodesPage.php | 7 +++++ lib/Reconciliation.php | 8 +++-- locales/po/cacti.pot | 5 +++ tests/Unit/InventoryPageTest.php | 17 ++++++++++ tests/Unit/RepositoryTest.php | 54 ++++++++++++++++++++++++++++++-- tests/bootstrap-unit.php | 17 ++++++++++ 11 files changed, 161 insertions(+), 14 deletions(-) diff --git a/gpu_nodes.php b/gpu_nodes.php index 856cc59..6ab6a63 100644 --- a/gpu_nodes.php +++ b/gpu_nodes.php @@ -51,7 +51,12 @@ exit; } - if (!$gpu_nodes->deviceExists($gpu_host)) { + // Keeping the recorded device is always allowed, even once it was + // deleted, so a node can still be disabled; a change must name a + // device that exists. + $gpu_same_host = $gpu_node !== null && $gpu_host === $gpu_node->hostId; + + if (!$gpu_same_host && !$gpu_nodes->deviceExists($gpu_host)) { $gpu_errors['host_id'] = __('Device: choose an existing Cacti device.', 'gpu'); } elseif ($gpu_nodes->hostTaken($gpu_host, $gpu_id)) { $gpu_errors['host_id'] = __('Device: this device is already a GPU node.', 'gpu'); diff --git a/lib/GpuRepository.php b/lib/GpuRepository.php index 27effe8..fdd56c5 100644 --- a/lib/GpuRepository.php +++ b/lib/GpuRepository.php @@ -32,9 +32,12 @@ public function __construct(private readonly \PDO|false $connection) { * The records IdentityReconciler needs for one snapshot: everything at the * node, and any record elsewhere that the snapshot reports. * - * @return list + * Null when the read fails: an empty list would make every reported GPU + * look new and lose the replacement link a stored record provides. + * + * @return list|null */ - public function forReconcile(Node $node, GpuSnapshot $snapshot): array { + public function forReconcile(Node $node, GpuSnapshot $snapshot): ?array { $uuids = $snapshot->uuids(); $sql = 'SELECT * FROM plugin_gpu_gpu WHERE node_id = ?'; @@ -42,7 +45,9 @@ public function forReconcile(Node $node, GpuSnapshot $snapshot): array { $sql .= ' OR uuid IN (' . implode(', ', array_fill(0, count($uuids), '?')) . ')'; } - return $this->records(db_fetch_assoc_prepared($sql . ' ORDER BY id', array_merge([$node->id], $uuids), true, $this->connection)); + $rows = db_fetch_assoc_prepared($sql . ' ORDER BY id', array_merge([$node->id], $uuids), true, $this->connection); + + return is_array($rows) ? $this->records($rows) : null; } /** @@ -63,6 +68,12 @@ public function pendingMoves(): array { * Write a reconciliation. Each statement stands alone and the next * collection recomputes from what was stored, so a run stopped part way * leaves records that the next run completes rather than corrupts. + * + * An update is written only while the record still has the node and + * pending node it was read with. An operator who confirms or rejects a + * move between the read and the write changes one of them, and the stale + * update then matches no row instead of undoing the operator's choice; + * the next collection recomputes from the stored state. */ public function apply(Reconciliation $changes): bool { $ok = true; @@ -73,13 +84,29 @@ public function apply(Reconciliation $changes): bool { } foreach ($changes->updated as $record) { + $read = $changes->read[$record->id] ?? null; + + // Without the state it was computed from, an update cannot be + // checked, so it is not written. + if ($read === null) { + $ok = false; + + continue; + } + $row = $record->toRow(); // Vendor and UUID are the key; an update never rewrites them. unset($row['vendor'], $row['uuid']); - $set = implode(', ', array_map(static fn (string $column): string => "$column = ?", array_keys($row))); - $ok = db_execute_prepared("UPDATE plugin_gpu_gpu SET $set WHERE id = ?", array_merge(array_values($row), [$record->id]), true, $this->connection) && $ok; + $set = implode(', ', array_map(static fn (string $column): string => "$column = ?", array_keys($row))); + $written = db_execute_prepared("UPDATE plugin_gpu_gpu SET $set WHERE id = ? AND node_id = ? AND pending_node_id = ?", array_merge(array_values($row), [$record->id, $read->nodeId, $read->pendingNodeId]), true, $this->connection); + + if (!$written) { + $ok = false; + } elseif (db_affected_rows($this->connection) === 0) { + Log::debug(sprintf('GPU record %d changed after it was read, so this collection left it alone', $record->id)); + } } return $ok; diff --git a/lib/IdentityReconciler.php b/lib/IdentityReconciler.php index 63b7672..7964579 100644 --- a/lib/IdentityReconciler.php +++ b/lib/IdentityReconciler.php @@ -80,7 +80,13 @@ public function reconcile(Node $node, array $known, GpuSnapshot $snapshot, int $ } } - return new Reconciliation($created, $updated); + $read = []; + + foreach ($known as $record) { + $read[$record->id] = $record; + } + + return new Reconciliation($created, $updated, $read); } /** diff --git a/lib/Inventory.php b/lib/Inventory.php index ba0d85a..32d74d1 100644 --- a/lib/Inventory.php +++ b/lib/Inventory.php @@ -33,7 +33,15 @@ public function __construct( } public function record(Node $node, GpuSnapshot $snapshot, int $absentAfter): Reconciliation { - $changes = $this->reconciler->reconcile($node, $this->gpus->forReconcile($node, $snapshot), $snapshot, $absentAfter, $this->clock->now()); + $known = $this->gpus->forReconcile($node, $snapshot); + + if ($known === null) { + Log::warning(sprintf('The GPU records for node %d could not be read, so this collection was not recorded', $node->id)); + + return new Reconciliation(); + } + + $changes = $this->reconciler->reconcile($node, $known, $snapshot, $absentAfter, $this->clock->now()); if ($changes->isEmpty()) { return $changes; diff --git a/lib/InventoryExport.php b/lib/InventoryExport.php index e7322a8..1670193 100644 --- a/lib/InventoryExport.php +++ b/lib/InventoryExport.php @@ -45,6 +45,9 @@ public static function json(array $nodes, array $gpus, string $pluginVersion, in 'gpus' => array_map(static fn (GpuRecord $gpu): array => ['id' => $gpu->id] + $gpu->toRow(), $gpus), ]; - return json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR) . "\n"; + // JSON_HEX_TAG: csrf-magic's output handler treats any response holding + // "