pax_global_header00006660000000000000000000000064132112146060014506gustar00rootroot0000000000000052 comment=6ac6c4ddb9e18c6e9c70aaaf3b24cac3886be542 python-protobix-1.0.1/000077500000000000000000000000001321121460600146725ustar00rootroot00000000000000python-protobix-1.0.1/.gitignore000066400000000000000000000001301321121460600166540ustar00rootroot00000000000000.coverage .cache *.pyc *.swp /__pycache__/ /.eggs/ MANIFEST dist/ *.egg-info *.xdb *.db python-protobix-1.0.1/.travis.yml000066400000000000000000000003161321121460600170030ustar00rootroot00000000000000language: python python: - "2.7" - "3.4" - "3.5" # comand to install requirements install: pip install -r requirements.txt -r requirements-test.txt # command to run tests script: python setup.py test python-protobix-1.0.1/LICENSE.txt000066400000000000000000001045131321121460600165210ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . python-protobix-1.0.1/README.md000066400000000000000000000250411321121460600161530ustar00rootroot00000000000000# python-protobix * `dev` Branch: [![Build Status](https://travis-ci.org/jbfavre/python-protobix.svg?branch=dev)](https://travis-ci.org/jbfavre/python-protobix) * `upstream` Branch (default): [![Build Status](https://travis-ci.org/jbfavre/python-protobix.svg?branch=upstream)](https://travis-ci.org/jbfavre/python-protobix) `python-protobix` is a very simple python module which implements [Zabbix Sender protocol 2.0](https://www.zabbix.org/wiki/Docs/protocols/zabbix_sender/2.0). It allows to build a list of Zabbix items and send them as `trappers`. Currently `python-protobix` supports "classics" `items` as well as [`Low Level Discovery`](https://www.zabbix.com/documentation/2.4/manual/discovery/low_level_discovery) ones. Please note that `python-protobix` is developped and tested on Debian GNU/Linux only. I can't enforce compatibility with other distributions, though it should work on any distribution providing Python 2.7 or Python 3.x. Any feedback on this is, of course, welcomed. ## Test To install all required dependencies and launch test suite python setup.py test By default, all tests named like `*need_backend*` are disabled, since they need a working Zabbix Server. If you want to run theses tests as well, you will need: * a working Zabbix Server 3.x configuration file like the one in `tests/zabbix/zabbix_server.conf` * SQL statements in `tests/zabbix/zabbix_server_mysql.sql` with all informations to create testing hosts & items You can then start Zabbix Server with `zabbix_server -c tests/zabbix/zabbix_server.conf -f` and launch test suite with py.test --cov protobix --cov-report term-missing ### Using a docker container You can also use docker to run test suite on any Linux distribution of your choice. You can use provided script `docker-tests.sh` as entrypoint example: docker run --volume=$(pwd):/home/python-protobix --entrypoint=/home/python-protobix/tests/docker-tests.sh -ti debian:jessie Currently, entrypoint `docker-tests.sh` only supports Debian GNU/Linux. __Please note that this docker entrypoint does not provide a way to execute test that need a backend__. ## Installation With `pip` (stable version): pip install protobix With `pip` (test version): pip install -i https://testpypi.python.org/simple/ protobix Python is available as Debian package for Debian GNU/Linux sid and testing. ## Usage Once module is installed, you can use it either extending `protobix.SampleProbe` or directly using `protobix.Datacontainer`. ### Extend `protobix.SampleProbe` `python-protobix` provides a convenient sample probe you can extend to fit your own needs. Using `protobix.SampleProbe` allows you to concentrate on getting metrics or Low Level Discovery items without taking care of anything related to `protobix` itself. This is the recommanded way of using `python-protobix`. `protobix.SampleProbe` provides a `run` method which take care of everything related to `protobix`. Some probes are available from my Github repository [`python-zabbix`](https://github.com/jbfavre/python-zabbix) ```python #!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright (c) 2013 Jean Baptiste Favre. Sample Python class which extends protobix.SampleProbe ''' import protobix import argparse import socket import sys class ExampleProbe(protobix.SampleProbe): __version__ = '1.0.1' # discovery_key is *not* the one declared in Zabbix Agent configuration # it's the one declared in Zabbix template's "Discovery rules" discovery_key = "example.probe.llddiscovery" def _parse_probe_args(self, parser): # Parse the script arguments # parser is an instance of argparse.parser created by SampleProbe._parse_args method # you *must* return parser to SampleProbe so that your own options are taken into account example_probe_options = parser.add_argument_group('ExampleProbe configuration') example_probe_options.add_argument( "-o", "--option", default="default_value", help="WTF do this option" ) return parser def _init_probe(self): # Whatever you need to initiliaze your probe # Can be establishing a connection # Or reading a configuration file # If you have nothing special to do # Just do not override this method # Or use: pass def _get_discovery(self): # Whatever you need to do to discover LLD items # this method is mandatory # If not declared, calling the probe ith --discovery option will resut in a NotimplementedError # If you get discovery infos for only one node you should return data as follow return { self.hostname: data } # If you get discovery infos for many hosts, then you should build data dict by yourself # and return result as follow return data def _get_metrics(self): # Whatever you need to do to collect metrics # this method is mandatory # If not declared, calling the probe with --update-items option will resut in a NotimplementedError # If you get metrics for only one node you should return data as follow return { self.hostname: data } # If you get metrics for many hosts, then you should build data dict by your self # and return result as follow return data if __name__ == '__main__': ret = RedisServer().run() print ret sys.exit(ret) ``` Declare your newly created probe as `Zabbix Agent` user parameters: UserParameter=example.probe.check,/usr/local/bin/example_probe.py --update-items UserParameter=example.probe.discovery,/usr/local/bin/example_probe.py --discovery You're done. The `protobix.SampleProbe` exit code will be sent to Zabbix. You'll be able to setup triggers if needed. __Exit codes mapping__: * 0: everything went well * 1: probe failed at step 1 (probe initialization) * 2: probe failed at step 2 (probe data collection) * 3: probe failed at step 3 (add data to DataContainer) * 4: probe failed at step 4 (send data to Zabbix) ### Use `protobix.Datacontainer` If you don't want or can't use `protobix.SampleProbe`, you can also directly use `protobix.Datacontainer`. __How to send items updates__ ```python #!/usr/bin/env python ''' import module ''' import protobix DATA = { "protobix.host1": { "my.protobix.item.int": 0, "my.protobix.item.string": "item string" }, "protobix.host2": { "my.protobix.item.int": 0, "my.protobix.item.string": "item string" } } zbx_datacontainer = protobix.DataContainer() zbx_datacontainer.data_type = 'items' zbx_datacontainer.add(DATA) zbx_datacontainer.send() ``` __How to send Low Level Discovery__ ```python #!/usr/bin/env python ''' import module ''' import protobix DATA = { 'protobix.host1': { 'my.protobix.lld_item1': [ { '{#PBX_LLD_KEY11}': 0, '{#PBX_LLD_KEY12}': 'lld string' }, { '{#PBX_LLD_KEY11}': 1, '{#PBX_LLD_KEY12}': 'another lld string' } ], 'my.protobix.lld_item2': [ { '{#PBX_LLD_KEY21}': 10, '{#PBX_LLD_KEY21}': 'yet an lld string' }, { '{#PBX_LLD_KEY21}': 2, '{#PBX_LLD_KEY21}': 'yet another lld string' } ] }, 'protobix.host2': { 'my.protobix.lld_item1': [ { '{#PBX_LLD_KEY11}': 0, '{#PBX_LLD_KEY12}': 'lld string' }, { '{#PBX_LLD_KEY11}': 1, '{#PBX_LLD_KEY12}': 'another lld string' } ], 'my.protobix.lld_item2': [ { '{#PBX_LLD_KEY21}': 10, '{#PBX_LLD_KEY21}': 'yet an lld string' }, { '{#PBX_LLD_KEY21}': 2, '{#PBX_LLD_KEY21}': 'yet another lld string' } ] } } zbx_datacontainer = protobix.DataContainer() zbx_datacontainer.data_type = 'lld' zbx_datacontainer.add(DATA) zbx_datacontainer.send() ``` ## Advanced configuration `python-protobix` behaviour can be altered in many ways using options. All configuration options are stored in a `protobix.ZabbixAgentConfig` instance. __Protobix specific configuration options__ | Option name | Default value | ZabbixAgentConfig property | Command-line option (SampleProbe) | |--------------|---------------|----------------------------|-----------------------------------| | `data_type` | `None` | `data_type` | `--update-items` or `--discovery` | | `dryrun` | `False` | `dryrun` | `-d` or `--dryrun` | __Zabbix Agent configuration options__ | Option name | Default value | ZabbixAgentConfig property | Command-line option (SampleProbe) | |------------------------|--------------------------|----------------------------|-----------------------------------| | `ServerActive` | `127.0.0.1` | `server_active` | `-z` or `--zabbix-server` | | `ServerPort` | `10051` | `server_port` | `-p` or `--port` | | `LogType` | `file` | `log_type` | none | | `LogFile` | `/tmp/zabbix_agentd.log` | `log_file` | none | | `DebugLevel` | `3` | `debug_level` | `-v` (from none to `-vvvvv`) | | `Timeout` | `3` | `timeout` | none | | `Hostname` | `socket.getfqdn()` | `hostname` | none | | `TLSConnect` | `unencrypted` | `tls_connect` | `--tls-connect` | | `TLSCAFile` | `None` | `tls_ca_file` | `--tls-ca-file` | | `TLSCertFile` | `None` | `tls_cert_file` | `--tls-cert-file` | | `TLSCRLFile` | `None` | `tls_crl_file` | `--tls-crl-file` | | `TLSKeyFile` | `None` | `tls_key_file` | `--tls-key-file` | | `TLSServerCertIssuer` | `None` | `tls_server_cert_issuer` | `--tls-server-cert-issuer` | | `TLSServerCertSubject` | `None` | `tls_server_cert_subject` | `--tls-server-cert-subject` | ## How to contribute You can contribute to `protobix`: * fork this repository * write tests and documentation (tests __must__ pass for both Python 2.7 & 3.x) * implement the feature you need * open a pull request against __`upstream`__ branch python-protobix-1.0.1/protobix/000077500000000000000000000000001321121460600165405ustar00rootroot00000000000000python-protobix-1.0.1/protobix/__init__.py000066400000000000000000000005031321121460600206470ustar00rootroot00000000000000""" Protobix is a simple module which implement Zabbix Sender protocol It provides a sample probe you can extend to monitor any software with Zabbix """ from .datacontainer import DataContainer from .senderprotocol import SenderProtocol from .sampleprobe import SampleProbe from .zabbixagentconfig import ZabbixAgentConfig python-protobix-1.0.1/protobix/datacontainer.py000066400000000000000000000204261321121460600217320ustar00rootroot00000000000000import logging try: import simplejson as json except ImportError: import json # pragma: no cover from .zabbixagentconfig import ZabbixAgentConfig from .senderprotocol import SenderProtocol # For both 2.0 & >2.2 Zabbix version # ? 1.8: Processed 0 Failed 1 Total 1 Seconds spent 0.000057 # 2.0: Processed 0 Failed 1 Total 1 Seconds spent 0.000057 # 2.2: processed: 50; failed: 1000; total: 1050; seconds spent: 0.09957 # 2.4: processed: 50; failed: 1000; total: 1050; seconds spent: 0.09957 ZBX_DBG_SEND_RESULT = "Send result [%s-%s-%s] for key [%s] item [%s]. Server's response is %s" ZBX_TRAPPER_MAX_VALUE = 250 class DataContainer(SenderProtocol): _items_list = [] _result = [] _logger = None _config = None socket = None def __init__(self, config=None, logger=None): # Loads config from zabbix_agentd file # If no file, it uses the default _config as configuration self._config = config if config is None: self._config = ZabbixAgentConfig() if logger: self.logger = logger self._items_list = [] def add_item(self, host, key, value, clock=None, state=0): """ Add a single item into DataContainer :host: hostname to which item will be linked to :key: item key as defined in Zabbix :value: item value :clock: timestemp as integer. If not provided self.clock()) will be used """ if clock is None: clock = self.clock if self._config.data_type == "items": item = {"host": host, "key": key, "value": value, "clock": clock, "state": state} elif self._config.data_type == "lld": item = {"host": host, "key": key, "clock": clock, "state": state, "value": json.dumps({"data": value})} else: if self.logger: # pragma: no cover self.logger.error("Setup data_type before adding data") raise ValueError('Setup data_type before adding data') self._items_list.append(item) def add(self, data): """ Add a list of item into the container :data: dict of items & value per hostname """ for host in data: for key in data[host]: if not data[host][key] == []: self.add_item(host, key, data[host][key]) def send(self): """ Entrypoint to send data to Zabbix If debug is enabled, items are sent one by one If debug isn't enable, we send items in bulk Returns a list of results (1 if no debug, as many as items in other case) """ if self.logger: # pragma: no cover self.logger.info("Starting to send %d items" % len(self._items_list)) try: # Zabbix trapper send a maximum of 250 items in bulk # We have to respect that, in case of enforcement on zabbix server side # Special case if debug is enabled: we need to send items one by one max_value = ZBX_TRAPPER_MAX_VALUE if self.debug_level >= 4: max_value = 1 if self.logger: # pragma: no cover self.logger.debug("Bulk limit is %d items" % max_value) else: if self.logger: # pragma: no cover self.logger.info("Bulk limit is %d items" % max_value) # Initialize offsets & counters max_offset = len(self._items_list) run = 0 start_offset = 0 stop_offset = min(start_offset + max_value, max_offset) server_success = server_failure = processed = failed = total = time = 0 while start_offset < stop_offset: run += 1 if self.logger: # pragma: no cover self.logger.debug( 'run %d: start_offset is %d, stop_offset is %d' % (run, start_offset, stop_offset) ) # Extract items to be send from global item's list' _items_to_send = self.items_list[start_offset:stop_offset] # Send extracted items run_response, run_processed, run_failed, run_total, run_time = self._send_common(_items_to_send) # Update counters if run_response == 'success': server_success += 1 elif run_response == 'failed': server_failure += 1 processed += run_processed failed += run_failed total += run_total time += run_time if self.logger: # pragma: no cover self.logger.info("%d items sent during run %d" % (run_total, run)) self.logger.debug( 'run %d: processed is %d, failed is %d, total is %d' % (run, run_processed, run_failed, run_total) ) # Compute next run's offsets start_offset = stop_offset stop_offset = min(start_offset + max_value, max_offset) # Reset socket, which is likely to be closed by server self._socket_reset() except: self._reset() self._socket_reset() raise if self.logger: # pragma: no cover self.logger.info('All %d items have been sent in %d runs' % (total, run)) self.logger.debug( 'Total run is %d; item processed: %d, failed: %d, total: %d, during %f seconds' % (run, processed, failed, total, time) ) # Everything has been sent. # Reset DataContainer & return results_list self._reset() return server_success, server_failure, processed, failed, total, time def _send_common(self, item): """ Common part of sending operations Calls SenderProtocol._send_to_zabbix Returns result as provided by _handle_response :item: either a list or a single item depending on debug_level """ total = len(item) processed = failed = time = 0 if self._config.dryrun is True: total = len(item) processed = failed = time = 0 response = 'dryrun' else: self._send_to_zabbix(item) response, processed, failed, total, time = self._read_from_zabbix() output_key = '(bulk)' output_item = '(bulk)' if self.debug_level >= 4: output_key = item[0]['key'] output_item = item[0]['value'] if self.logger: # pragma: no cover self.logger.info( "" + ZBX_DBG_SEND_RESULT % ( processed, failed, total, output_key, output_item, response ) ) return response, processed, failed, total, time def _reset(self): """ Reset main DataContainer properties """ # Reset DataContainer to default values # So that it can be reused if self.logger: # pragma: no cover self.logger.info("Reset DataContainer") self._items_list = [] self._config.data_type = None @property def logger(self): """ Returns logger instance """ return self._logger @logger.setter def logger(self, value): """ Set logger instance for the class """ if isinstance(value, logging.Logger): self._logger = value else: if self._logger: # pragma: no cover self._logger.error("logger requires a logging instance") raise ValueError('logger requires a logging instance') # ZabbixAgentConfig getter & setter # Avoid using private property _config from outside @property def dryrun(self): """ Returns dryrun """ return self._config.dryrun @dryrun.setter def dryrun(self, value): """ Set dryrun """ self._config.dryrun = value @dryrun.setter def data_type(self, value): """ Set data_type """ self._config.data_type = value python-protobix-1.0.1/protobix/sampleprobe.py000077500000000000000000000323571321121460600214400ustar00rootroot00000000000000import argparse from argparse import RawTextHelpFormatter import socket import sys import traceback import logging from logging import handlers from .datacontainer import DataContainer from .zabbixagentconfig import ZabbixAgentConfig class SampleProbe(object): __version__ = '1.0.1' # Mapping between zabbix-agent Debug option & logging level LOG_LEVEL = [ logging.NOTSET, logging.CRITICAL, logging.ERROR, logging.INFO, logging.DEBUG, logging.DEBUG, ] logger = None probe_config = None hostname = None options = None def _parse_args(self, args): if self.logger: self.logger.info( "Read command line options" ) # Parse the script arguments parser = argparse.ArgumentParser( usage='%(prog)s [options]', formatter_class=RawTextHelpFormatter, epilog='Protobix - copyright 2016 - Jean Baptiste Favre (www.jbfavre.org)' ) # Probe operation mode probe_mode = parser.add_argument_group('Probe commands') probe_mode.add_argument( '--update-items', action='store_true', dest='update', help="Get & send items to Zabbix.\nThis is the default behaviour" ) probe_mode.add_argument( '--discovery', action='store_true', help="If specified, will perform Zabbix Low Level Discovery." ) # Common options common = parser.add_argument_group('Common options') common.add_argument( '-d', '--dryrun', action='store_true', help="Do not send anything to Zabbix. Usefull to debug with\n" "--verbose option" ) common.add_argument( '-v', action='count', dest='debug_level', help="Enable verbose mode. Is used to setup logging level.\n" "Specifying 4 or more 'v' (-vvvv) enables Debug. Items are then\n" "sent one after the other instead of bulk" ) # Protobix specific options protobix = parser.add_argument_group('Protobix specific options') protobix.add_argument( '-z', '--zabbix-server', dest='server_active', help="Hostname or IP address of Zabbix server. If a host is\n" "monitored by a proxy, proxy hostname or IP address\n" "should be used instead. When used together with\n" "--config, overrides the first entry of ServerActive\n" "parameter specified in agentd configuration file." ) protobix.add_argument( '-p', '--port', dest='server_port', help="Specify port number of Zabbix server trapper running on\n" "the server. Default is 10051. When used together with \n" "--config, overrides the port of first entry of\n" "ServerActive parameter specified in agentd configuration\n" "file." ) protobix.add_argument( '-c', '--config', dest='config_file', help="Use config-file. Zabbix sender reads server details from\n" "the agentd configuration file. By default Protobix reads\n" "`/etc/zabbix/zabbix_agentd.conf`.\n" "Absolute path should be specified." ) protobix.add_argument( '--tls-connect', choices=['unencrypted', 'psk', 'cert'], help="How to connect to server or proxy. Values:\n" "unencrypted connect without encryption\n" "psk connect using TLS and a pre-shared key\n" "cert connect using TLS and a certificate." ) protobix.add_argument( '--tls-ca-file', help="Full pathname of a file containing the top-level CA(s)\n" "certificates for peer certificate verification." ) protobix.add_argument( '--tls-cert-file', help="Full pathname of a file containing the certificate or\n" "certificate chain." ) protobix.add_argument( '--tls-key-file', help="Full pathname of a file containing the private key." ) protobix.add_argument( '--tls-crl-file', help="Full pathname of a file containing revoked certificates." ) protobix.add_argument( '--tls-server-cert-issuer', help="Allowed server certificate issuer." ) protobix.add_argument( '--tls-server-cert-subject', help="Allowed server certificate subject." ) # TLS PSK is not implemented in Python # https://bugs.python.org/issue19084 # Following options are not implemented protobix.add_argument( '--tls-psk-identity', help="PSK-identity string." ) protobix.add_argument( '--tls-psk-file', help="Full pathname of a file containing the pre-shared key." ) # Probe specific options parser = self._parse_probe_args(parser) # Analyze provided command line options options = parser.parse_args(args) # Check that we don't have both '--update' & '--discovery' options options.probe_mode = 'update' if options.update is True and options.discovery is True: raise ValueError( 'You can\' use both --update-items & --discovery options' ) elif options.discovery is True: options.probe_mode = 'discovery' return options def _init_logging(self): logger = logging.getLogger(self.__class__.__name__) logger.handlers = [] logger.setLevel(logging.NOTSET) self.logger = logger def _setup_logging(self, log_type, debug_level, log_file): if self.logger: self.logger.info( "Initialize logging" ) # Enable log like Zabbix Agent does # Though, when we have a tty, it's convenient to use console to log common_log_format = '[%(name)s:%(levelname)s] %(message)s' if log_type == 'console' or sys.stdout.isatty(): console_handler = logging.StreamHandler() console_formatter = logging.Formatter( fmt=common_log_format, datefmt='%Y%m%d:%H%M%S' ) console_handler.setFormatter(console_formatter) self.logger.addHandler(console_handler) if log_type == 'file': file_handler = logging.FileHandler(log_file) # Use same date format as Zabbix: when logging into # zabbix_agentd log file, it's easier to read & parse log_formatter = logging.Formatter( fmt='%(process)d:%(asctime)s.%(msecs)03d ' + common_log_format, datefmt='%Y%m%d:%H%M%S' ) file_handler.setFormatter(log_formatter) self.logger.addHandler(file_handler) if log_type == 'system': # TODO: manage syslog address as command line option syslog_handler = logging.handlers.SysLogHandler( address=('localhost', 514), facility=logging.handlers.SysLogHandler.LOG_DAEMON ) # Use same date format as Zabbix does: when logging into # zabbix_agentd log file, it's easier to read & parse log_formatter = logging.Formatter( fmt='%(process)d:%(asctime)s.%(msecs)03d ' + common_log_format, datefmt='%Y%m%d:%H%M%S' ) syslog_handler.setFormatter(log_formatter) self.logger.addHandler(syslog_handler) self.logger.setLevel( self.LOG_LEVEL[debug_level] ) def _init_config(self): if self.logger: self.logger.info( "Get configuration" ) # Get config from ZabbixAgentConfig zbx_config = ZabbixAgentConfig(self.options.config_file) # And override it with provided command line options if self.options.server_active: zbx_config.server_active = self.options.server_active if self.options.server_port: zbx_config.server_port = int(self.options.server_port) # tls_connect 'cert' needed options if self.options.tls_cert_file: zbx_config.tls_cert_file = self.options.tls_cert_file if self.options.tls_key_file: zbx_config.tls_key_file = self.options.tls_key_file if self.options.tls_ca_file: zbx_config.tls_ca_file = self.options.tls_ca_file if self.options.tls_crl_file: zbx_config.tls_crl_file = self.options.tls_crl_file # tls_connect 'psk' needed options if self.options.tls_psk_file: zbx_config.tls_psk_file = self.options.tls_psk_file if self.options.tls_psk_identity: zbx_config.tls_psk_identity = self.options.tls_psk_identity if self.options.tls_server_cert_issuer: zbx_config.tls_server_cert_issuer = self.options.tls_server_cert_issuer if self.options.tls_server_cert_subject: zbx_config.tls_server_cert_subject = self.options.tls_server_cert_subject # Set tls_connect last because it'll check above options # to ensure a coherent config set if self.options.tls_connect: zbx_config.tls_connect = self.options.tls_connect if self.options.debug_level: self.options.debug_level = min(4, self.options.debug_level) zbx_config.debug_level = self.options.debug_level zbx_config.dryrun = False if self.options.dryrun: zbx_config.dryrun = self.options.dryrun return zbx_config def _get_metrics(self): # mandatory method raise NotImplementedError def _get_discovery(self): # mandatory method raise NotImplementedError def _init_probe(self): # non mandatory method pass def _parse_probe_args(self, parser): # non mandatory method return parser def run(self, options=None): # Init logging with default values since we don't have real config yet self._init_logging() # Parse command line options args = sys.argv[1:] if isinstance(options, list): args = options self.options = self._parse_args(args) # Get configuration self.zbx_config = self._init_config() # Update logger with configuration self._setup_logging( self.zbx_config.log_type, self.zbx_config.debug_level, self.zbx_config.log_file ) # Datacontainer init zbx_container = DataContainer( config = self.zbx_config, logger=self.logger ) # Get back hostname from ZabbixAgentConfig self.hostname = self.zbx_config.hostname # Step 1: read probe configuration # initialize any needed object or connection try: self._init_probe() except: if self.logger: self.logger.critical( "Step 1 - Read probe configuration failed" ) self.logger.debug(traceback.format_exc()) return 1 # Step 2: get data try: data = {} if self.options.probe_mode == "update": zbx_container.data_type = 'items' data = self._get_metrics() elif self.options.probe_mode == "discovery": zbx_container.data_type = 'lld' data = self._get_discovery() except NotImplementedError as e: if self.logger: self.logger.critical( "Step 2 - Get Data failed [%s]" % str(e) ) self.logger.debug(traceback.format_exc()) raise except Exception as e: if self.logger: self.logger.critical( "Step 2 - Get Data failed [%s]" % str(e) ) self.logger.debug(traceback.format_exc()) return 2 # Step 3: add data to container try: zbx_container.add(data) except Exception as e: if self.logger: self.logger.critical( "Step 3 - Format & add Data failed [%s]" % str(e) ) self.logger.debug(traceback.format_exc()) zbx_container._reset() return 3 # Step 4: send data to Zabbix server try: zbx_container.send() except socket.error as e: if self.logger: self.logger.critical( "Step 4 - Sent to Zabbix Server [%s] failed [%s]" % ( self.zbx_config.server_active, str(e) ) ) self.logger.debug(traceback.format_exc()) return 4 except Exception as e: if self.logger: self.logger.critical( "Step 4 - Unknown error [%s]" % str(e) ) self.logger.debug(traceback.format_exc()) return 4 # Everything went fine. Let's return 0 and exit return 0 python-protobix-1.0.1/protobix/senderprotocol.py000066400000000000000000000272371321121460600221670ustar00rootroot00000000000000import struct import sys import time import re import socket try: import simplejson as json except ImportError: import json # pragma: no cover from .zabbixagentconfig import ZabbixAgentConfig if sys.version_info < (3,): # pragma: no cover def b(x): return x else: # pragma: no cover import codecs def b(x): return codecs.utf_8_encode(x)[0] HAVE_DECENT_SSL = False if sys.version_info > (2,7,9): import ssl # Zabbix force TLSv1.2 protocol # in src/libs/zbxcrypto/tls.c function zbx_tls_init_child ZBX_TLS_PROTOCOL=ssl.PROTOCOL_TLSv1_2 HAVE_DECENT_SSL = True ZBX_HDR = "ZBXD\1" ZBX_HDR_SIZE = 13 ZBX_RESP_REGEX = r'[Pp]rocessed:? (\d+);? [Ff]ailed:? (\d+);? ' + \ r'[Tt]otal:? (\d+);? [Ss]econds spent:? (\d+\.\d+)' class SenderProtocol(object): REQUEST = "sender data" _logger = None def __init__(self, logger=None): self._config = ZabbixAgentConfig() self._items_list = [] self.socket = None if logger: # pragma: no cover self._logger = logger @property def server_active(self): return self._config.server_active @server_active.setter def server_active(self, value): if self._logger: # pragma: no cover self._logger.debug( "Replacing server_active '%s' with '%s'" % (self._config.server_active, value) ) self._config.server_active = value @property def server_port(self): return self._config.server_port @server_port.setter def server_port(self, value): if self._logger: # pragma: no cover self._logger.debug( "Replacing server_port '%s' with '%s'" % (self._config.server_port, value) ) self._config.server_port = value @property def debug_level(self): return self._config.debug_level @debug_level.setter def debug_level(self, value): if self._logger: # pragma: no cover self._logger.debug( "Replacing debug_level '%s' with '%s'" % (self._config.debug_level, value) ) self._config.debug_level = value @property def items_list(self): return self._items_list @property def clock(self): return int(time.time()) def _send_to_zabbix(self, item): if self._logger: # pragma: no cover self._logger.info( "Send data to Zabbix Server" ) # Format data to be sent if self._logger: # pragma: no cover self._logger.debug( "Building packet to be sent to Zabbix Server" ) payload = json.dumps({"data": item, "request": self.REQUEST, "clock": self.clock }) if self._logger: # pragma: no cover self._logger.debug('About to send: ' + str(payload)) data_length = len(payload) data_header = struct.pack('= 4096: _buffer = self._socket().recv(4096) zbx_srv_resp_data += _buffer recv_length = len(_buffer) _buffer = None recv_length = None # Check that we have a valid Zabbix header mark if self._logger: # pragma: no cover self._logger.debug( "Checking Zabbix headers" ) assert zbx_srv_resp_data[:5] == b(ZBX_HDR) # Extract response body length from packet zbx_srv_resp_body_len = struct.unpack('= 3: # pragma: no cover zbx_srv_resp_body = zbx_srv_resp_body.decode() # Analyze Zabbix answer response, processed, failed, total, time = self._handle_response(zbx_srv_resp_body) # Return Zabbix Server answer as JSON return response, processed, failed, total, time def _handle_response(self, zbx_answer): """ Analyze Zabbix Server response Returns a list with number of: * processed items * failed items * total items * time spent :zbx_answer: Zabbix server response as string """ zbx_answer = json.loads(zbx_answer) if self._logger: # pragma: no cover self._logger.info( "Anaylizing Zabbix Server's answer" ) if zbx_answer: self._logger.debug("Zabbix Server response is: [%s]" % zbx_answer) # Default items number in length of th storage list nb_item = len(self._items_list) if self._config.debug_level >= 4: # If debug enabled, force it to 1 nb_item = 1 # If dryrun is disabled, we can process answer response = zbx_answer.get('response') result = re.findall(ZBX_RESP_REGEX, zbx_answer.get('info')) processed, failed, total, time = result[0] return response, int(processed), int(failed), int(total), float(time) def _socket_reset(self): if self.socket: if self._logger: # pragma: no cover self._logger.info( "Reset socket" ) self.socket.close() self.socket = None def _socket(self): # If socket already exists, use it if self.socket is not None: if self._logger: # pragma: no cover self._logger.debug( "Using existing socket" ) return self.socket # If not, we have to create it if self._logger: # pragma: no cover self._logger.debug( "Setting socket options" ) socket.setdefaulttimeout(self._config.timeout) # Connect to Zabbix server or proxy with provided config options if self._logger: # pragma: no cover self._logger.info( "Creating new socket" ) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TLS is enabled, let's set it up if self._config.tls_connect != 'unencrypted' and HAVE_DECENT_SSL is True: if self._logger: # pragma: no cover self._logger.info( 'Configuring TLS to %s' % str(self._config.tls_connect) ) # Setup TLS context & Wrap socket self.socket = self._init_tls() if self._logger: # pragma: no cover self._logger.info( 'Network socket initialized with TLS support' ) if self._logger and isinstance(self.socket, socket.socket): # pragma: no cover self._logger.info( 'Network socket initialized with no TLS' ) # Connect to Zabbix Server self.socket.connect( (self._config.server_active, self._config.server_port) ) #if isinstance(self.socket, ssl.SSLSocket): # server_cert = self.socket.getpeercert() # if self._config.tls_server_cert_issuer: # print(server_cert['issuer']) # assert server_cert['issuer'] == self._config.tls_server_cert_issuer # self._logger.info( # 'Server certificate issuer is %s' % # server_cert['issuer'] # ) # if self._config.tls_server_cert_subject: # print(server_cert['subject']) # assert server_cert['subject'] == self._config.tls_server_cert_subject # self._logger.info( # 'Server certificate subject is %s' % # server_cert['subject'] # ) return self.socket """ Manage TLS context & Wrap socket Returns ssl.SSLSocket if TLS enabled socket.socket if TLS disabled """ def _init_tls(self): # Create a SSLContext and configure it if self._logger: # pragma: no cover self._logger.info( "Initialize TLS context" ) ssl_context = ssl.SSLContext(ZBX_TLS_PROTOCOL) if self._logger: # pragma: no cover self._logger.debug( 'Setting TLS verify_mode to ssl.CERT_REQUIRED' ) ssl_context.verify_mode = ssl.CERT_REQUIRED # Avoid CRIME and related attacks if self._logger: # pragma: no cover self._logger.debug( 'Setting TLS option ssl.OP_NO_COMPRESSION' ) ssl_context.options |= ssl.OP_NO_COMPRESSION ssl_context.verify_flags = ssl.VERIFY_X509_STRICT # If tls_connect is cert, we must provide client cert file & key if self._config.tls_connect == 'cert': if self._logger: # pragma: no cover self._logger.debug( "Using provided TLSCertFile %s" % self._config.tls_cert_file ) self._logger.debug( "Using provided TLSKeyFile %s" % self._config.tls_key_file ) ssl_context.load_cert_chain( self._config.tls_cert_file, self._config.tls_key_file ) elif self._config.tls_connect == 'psk': raise NotImplementedError # If provided, use CA file & enforce server certificate chek if self._config.tls_ca_file: if self._logger: # pragma: no cover self._logger.debug( "Using provided TLSCAFile %s" % self._config.tls_ca_file ) ssl_context.load_default_certs(ssl.Purpose.SERVER_AUTH) ssl_context.load_verify_locations( cafile=self._config.tls_ca_file ) # If provided, use CRL file & enforce server certificate check if self._config.tls_crl_file: if self._logger: # pragma: no cover self._logger.debug( "Using provided TLSCRLFile %s" % self._config.tls_crl_file ) ssl_context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF ssl_context.load_verify_locations( cafile=self._config.tls_crl_file ) ## If provided enforce server cert issuer check #if self._config.tls_server_cert_issuer: # verify_issuer ## If provided enforce server cert subject check #if self._config.tls_server_cert_issuer: # verify_issuer # Once configuration is done, wrap network socket to TLS context tls_socket = ssl_context.wrap_socket( self.socket ) assert isinstance(tls_socket, ssl.SSLSocket) return tls_socket python-protobix-1.0.1/protobix/zabbixagentconfig.py000066400000000000000000000256751321121460600226150ustar00rootroot00000000000000import configobj import socket class ZabbixAgentConfig(object): _logger = None _default_config_file='/etc/zabbix/zabbix_agentd.conf' def __init__(self, config_file=None, logger=None): if config_file is None: config_file=self._default_config_file if logger: # pragma: no cover self._logger = logger if self._logger: # pragma: no cover self._logger.info( "Initializing" ) # Set default config value from sample zabbix_agentd.conf # Only exception is hostname. While non mandatory, we must have # This property set. Default goes to server FQDN # We do *NOT* support HostnameItem except to fake system.hostname self.config = { # Protobix specific options 'data_type': None, 'dryrun': False, # Zabbix Agent options 'ServerActive': '127.0.0.1', 'ServerPort': 10051, 'LogType': 'file', 'LogFile': '/tmp/zabbix_agentd.log', 'DebugLevel': 3, 'Timeout': 3, 'Hostname': socket.getfqdn(), 'TLSConnect': 'unencrypted', 'TLSCAFile': None, 'TLSCertFile': None, 'TLSCRLFile': None, 'TLSKeyFile': None, 'TLSServerCertIssuer': None, 'TLSServerCertSubject': None, 'TLSPSKIdentity': None, 'TLSPSKFile': None, } # list_values=False argument below is needed because of potential # UserParameter with spaces which breaks ConfigObj # See if self._logger: # pragma: no cover self._logger.debug( "Reading Zabbix Agent configuration file %s" % config_file ) tmp_config = configobj.ConfigObj(config_file, list_values=False) # If not config_file found or provided, # we should fallback to the default if tmp_config == {}: if self._logger: # pragma: no cover self._logger.warn( "Not configuration found" ) return if self._logger: # pragma: no cover self._logger.debug( "Setting configuration" ) if 'DebugLevel' in tmp_config: self.debug_level = int(tmp_config['DebugLevel']) if 'Timeout' in tmp_config: self.timeout = int(tmp_config['Timeout']) if 'Hostname' in tmp_config: self.hostname = tmp_config['Hostname'] # Process LogType & LogFile & ServerACtive in separate methods # Due to custom logic self._process_server_config(tmp_config) self._process_log_config(tmp_config) self._process_tls_config(tmp_config) def _process_server_config(self, tmp_config): if self._logger: # pragma: no cover self._logger.debug( "Processing server config" ) if 'ServerActive' in tmp_config: # Because of list_values=False above, # we have to check ServerActive format # and extract server & port manually # See https://github.com/jbfavre/python-protobix/issues/16 tmp_server = tmp_config['ServerActive'].split(',')[0] \ if "," in tmp_config['ServerActive'] else tmp_config['ServerActive'] self.server_active, server_port = \ tmp_server.split(':') if ":" in tmp_server else (tmp_server, 10051) self.server_port = int(server_port) def _process_log_config(self, tmp_config): if self._logger: # pragma: no cover self._logger.debug( "Processing log config" ) if 'LogType' in tmp_config and tmp_config['LogType'] in ['file', 'system', 'console']: self.log_type = tmp_config['LogType'] elif 'LogType' in tmp_config: raise ValueError('LogType must be one of [file,system,console]') # At this point, LogType is one of [file,system,console] if self.log_type in ['system', 'console']: # If LogType if console or system, we don't need LogFile self.log_file = None elif self.log_type == 'file': # LogFile will be used if 'LogFile' in tmp_config and tmp_config['LogFile'] == '-': # Zabbix 2.4 compatibility # LogFile to '-' means we want to use syslog self.log_file = None self.log_type = 'system' elif 'LogFile' in tmp_config: self.log_file = tmp_config['LogFile'] def _process_tls_config(self, tmp_config): if self._logger: # pragma: no cover self._logger.debug( "Processing tls config" ) if 'TLSConnect' in tmp_config: self.tls_connect = tmp_config['TLSConnect'] if self.tls_connect == 'cert': if 'TLSCertFile' in tmp_config and \ 'TLSKeyFile' in tmp_config and \ 'TLSCAFile' in tmp_config: self.tls_cert_file = tmp_config['TLSCertFile'] self.tls_key_file = tmp_config['TLSKeyFile'] self.tls_ca_file = tmp_config['TLSCAFile'] else: raise ValueError('TLSConnect is cert. TLSCertFile, TLSKeyFile and TLSCAFile are mandatory') if 'TLSCRLFile' in tmp_config: self.tls_crl_file = tmp_config['TLSCRLFile'] if 'TLSServerCertIssuer' in tmp_config: self.tls_server_cert_issuer = tmp_config['TLSServerCertIssuer'] if 'TLSServerCertSubject' in tmp_config: self.tls_server_cert_subject = tmp_config['TLSServerCertSubject'] if self.tls_connect == 'psk': if 'TLSPSKIdentity' in tmp_config and 'TLSPSKFile' in tmp_config: self.tls_psk_identity = tmp_config['TLSPSKIdentity'] self.tls_psk_file = tmp_config['TLSPSKFile'] else: raise ValueError('TLSConnect is psk. TLSPSKIdentity and TLSPSKFile are mandatory') @property def server_active(self): return self.config['ServerActive'] @server_active.setter def server_active(self, value): if value: self.config['ServerActive'] = value @property def server_port(self): return self.config['ServerPort'] @server_port.setter def server_port(self, value): # Must between 1024-32767 like ListenPort for Server & Proxy # https://www.zabbix.com/documentation/3.0/manual/appendix/config/zabbix_server if isinstance(value, int) and value >= 1024 and value <= 32767: self.config['ServerPort'] = value else: raise ValueError('ServerPort must be between 1024 and 32767') @property def log_type(self): if 'LogType' in self.config: return self.config['LogType'] @log_type.setter def log_type(self, value): if value and value in ['file', 'system', 'console']: self.config['LogType'] = value @property def log_file(self): return self.config['LogFile'] @log_file.setter def log_file(self, value): self.config['LogFile'] = value @property def debug_level(self): return self.config['DebugLevel'] @debug_level.setter def debug_level(self, value): # Must be between 0 and 5 # https://www.zabbix.com/documentation/3.0/manual/appendix/config/zabbix_agentd if isinstance(value, int) and value >= 0 and value <= 5: self.config['DebugLevel'] = value else: raise ValueError('DebugLevel must be between 0 and 5, ' + str(value) + ' provided') @property def timeout(self): return self.config['Timeout'] @timeout.setter def timeout(self, value): # Must be between 1 and 30 # https://www.zabbix.com/documentation/3.0/manual/appendix/config/zabbix_agentd if isinstance(value, int) and value > 0 and value <= 30: self.config['Timeout'] = value else: raise ValueError('Timeout must be between 1 and 30') @property def hostname(self): return self.config['Hostname'] @hostname.setter def hostname(self, value): if value: self.config['Hostname'] = value @property def tls_connect(self): return self.config['TLSConnect'] @tls_connect.setter def tls_connect(self, value): if value in ['unencrypted', 'psk', 'cert']: self.config['TLSConnect'] = value else: raise ValueError('TLSConnect must be one of [unencrypted,psk,cert]') @property def tls_ca_file(self): return self.config['TLSCAFile'] @tls_ca_file.setter def tls_ca_file(self, value): if value: self.config['TLSCAFile'] = value @property def tls_cert_file(self): return self.config['TLSCertFile'] @tls_cert_file.setter def tls_cert_file(self, value): if value: self.config['TLSCertFile'] = value @property def tls_crl_file(self): return self.config['TLSCRLFile'] @tls_crl_file.setter def tls_crl_file(self, value): if value: self.config['TLSCRLFile'] = value @property def tls_key_file(self): return self.config['TLSKeyFile'] @tls_key_file.setter def tls_key_file(self, value): if value: self.config['TLSKeyFile'] = value @property def tls_server_cert_issuer(self): return self.config['TLSServerCertIssuer'] @tls_server_cert_issuer.setter def tls_server_cert_issuer(self, value): if value: self.config['TLSServerCertIssuer'] = value @property def tls_server_cert_subject(self): return self.config['TLSServerCertSubject'] @tls_server_cert_subject.setter def tls_server_cert_subject(self, value): if value: self.config['TLSServerCertSubject'] = value @property def tls_psk_identity(self): return self.config['TLSPSKIdentity'] @tls_psk_identity.setter def tls_psk_identity(self, value): if value: self.config['TLSPSKIdentity'] = value @property def tls_psk_file(self): return self.config['TLSPSKFile'] @tls_psk_file.setter def tls_psk_file(self, value): if value: self.config['TLSPSKFile'] = value @property def dryrun(self): return self.config['dryrun'] @dryrun.setter def dryrun(self, value): if value in [True, False]: self.config['dryrun'] = value else: raise ValueError('dryrun parameter requires boolean') @property def data_type(self): return self.config['data_type'] @data_type.setter def data_type(self, value): if value in ['lld', 'items', None]: self.config['data_type'] = value else: raise ValueError('data_type requires either "items" or "lld"') python-protobix-1.0.1/pytest.ini000066400000000000000000000000441321121460600167210ustar00rootroot00000000000000[pytest] addopts='-k-_need_backend' python-protobix-1.0.1/requirements-test.txt000066400000000000000000000000271321121460600211320ustar00rootroot00000000000000pytest pytest-cov mock python-protobix-1.0.1/requirements.txt000066400000000000000000000000251321121460600201530ustar00rootroot00000000000000configobj simplejson python-protobix-1.0.1/setup.cfg000066400000000000000000000000501321121460600165060ustar00rootroot00000000000000[metadata] description-file = README.md python-protobix-1.0.1/setup.py000077500000000000000000000017751321121460600164210ustar00rootroot00000000000000#!/usr/bin/env python import sys from setuptools import setup setup( name = 'protobix', packages = ['protobix'], version = '1.0.1', install_requires = [ 'configobj', 'simplejson' ], tests_require = [ 'mock', 'pytest', ], test_suite='tests', description = 'Implementation of Zabbix Sender protocol', long_description = ( 'This module implements Zabbix Sender Protocol.\n' 'It allows to build list of items and send ' 'them as trapper.\n' 'It currently supports items update as well as ' 'Low Level Discovery.' ), author = 'Jean Baptiste Favre', author_email = 'jean-baptiste.favre@blablacar.com', license = 'GPL-3+', url='https://github.com/jbfavre/python-protobix/', download_url = 'https://github.com/jbfavre/python-protobix/archive/1.0.1.tar.gz', keywords = ['monitoring','zabbix','trappers'], classifiers = [], ) python-protobix-1.0.1/tests/000077500000000000000000000000001321121460600160345ustar00rootroot00000000000000python-protobix-1.0.1/tests/__init__.py000066400000000000000000000007241321121460600201500ustar00rootroot00000000000000#!/usr/bin/env python import sys import pytest try: import coverage coverage_options = ['--cov', 'protobix', '--cov-report', 'term-missing'] except ImportError: coverage_options = [] try: import pylint pylint_options = ['--pylint ', '--pylint-error-types=WEF'] except ImportError: pylint_options = [] pytest_options = ['-v', '-k-_need_backend'] pytest_options += coverage_options pytest_options += pylint_options pytest.main(pytest_options) python-protobix-1.0.1/tests/docker-tests.sh000077500000000000000000000031501321121460600210010ustar00rootroot00000000000000#!/bin/bash VERSION=$(sed 's/\..*//' /etc/debian_version) case ${VERSION} in 7) echo 'Debian Wheezy' packages_list='python2.7 python-setuptools python-configobj python-simplejson python-pytest python-mock adduser' test_suite_list='python' ;; 8) echo 'Debian Jessie' packages_list='python2.7 python3 python-setuptools python3-setuptools python-configobj python-simplejson python3-configobj python3-simplejson python-pytest python-pytest-cov python-mock python3-pytest python3-pytest-cov python3-mock' test_suite_list='python python3' ;; *) echo 'Debian stretch/sid' packages_list='python2.7 python3 python-setuptools python3-setuptools python-configobj python-simplejson python3-configobj python3-simplejson python-pytest python-pytest-cov python-mock python3-pytest python3-pytest-cov python3-mock' test_suite_list='python python3' ;; esac function cleanup() { cd /home/python-protobix find . -name '*.pyc' -exec rm {} \; 2>/dev/null find . -name '__pycache__' -exec rm -r {} \; 2>/dev/null } # Update package list apt-get update # Install dependencies for both python 2.7 & python 3 apt-get -qq -y install ${packages_list} # Create an unprivileged user addgroup -gid 1000 protobix adduser --system -uid 1000 -gid 1000 --home /home/python-protobix \ --shell /bin/bash --no-create-home --disabled-password \ protobix for test_suite in ${test_suite_list} do # Clean existing cache files cleanup # Run test suite su - protobix -s /bin/bash -c "cd /home/python-protobix;${test_suite} setup.py test" done # Clean existing cache files cleanup python-protobix-1.0.1/tests/test_datacontainer.py000066400000000000000000000206111321121460600222610ustar00rootroot00000000000000""" Tests for protobix.SenderProtocol """ import configobj import pytest import mock import unittest import time try: import simplejson as json except ImportError: import json import socket import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) import protobix DATA = { 'items': { "protobix.host1": { "my.protobix.item.int": 0, "my.protobix.item.string": "item string" }, "protobix.host2": { "my.protobix.item.int": 0, "my.protobix.item.string": "item string" } }, 'lld': { 'protobix.host1': { 'my.protobix.lld_item1': [ { '{#PBX_LLD_KEY11}': 0, '{#PBX_LLD_KEY12}': 'lld string' }, { '{#PBX_LLD_KEY11}': 1, '{#PBX_LLD_KEY12}': 'another lld string' } ], 'my.protobix.lld_item2': [ { '{#PBX_LLD_KEY21}': 10, '{#PBX_LLD_KEY21}': 'yet an lld string' }, { '{#PBX_LLD_KEY21}': 2, '{#PBX_LLD_KEY21}': 'yet another lld string' } ] }, 'protobix.host2': { 'my.protobix.lld_item1': [ { '{#PBX_LLD_KEY11}': 0, '{#PBX_LLD_KEY12}': 'lld string' }, { '{#PBX_LLD_KEY11}': 1, '{#PBX_LLD_KEY12}': 'another lld string' } ], 'my.protobix.lld_item2': [ { '{#PBX_LLD_KEY21}': 10, '{#PBX_LLD_KEY21}': 'yet an lld string' }, { '{#PBX_LLD_KEY21}': 2, '{#PBX_LLD_KEY21}': 'yet another lld string' } ] } } } pytest_params = ( 'items', 'lld' ) def test_invalid_logger(): """ Adding data before assigning data_type should raise an Exception """ with pytest.raises(ValueError) as err: zbx_datacontainer = protobix.DataContainer(logger='invalid') assert str(err.value) == 'logger requires a logging instance' @pytest.mark.parametrize('data_type', pytest_params) def test_items_add_before_set_data_type(data_type): """ Adding data before assigning data_type should raise an Exception """ zbx_datacontainer = protobix.DataContainer() assert zbx_datacontainer.items_list == [] with pytest.raises(ValueError): zbx_datacontainer.add(DATA[data_type]) assert zbx_datacontainer.items_list == [] zbx_datacontainer.data_type = data_type zbx_datacontainer.add(DATA) assert len(zbx_datacontainer.items_list) == 4 @pytest.mark.parametrize('data_type', pytest_params) def test_debug_no_dryrun_yes(data_type): """ debug_level to False dryrun to True """ zbx_datacontainer = protobix.DataContainer() zbx_datacontainer.data_type = data_type zbx_datacontainer.dryrun = True assert zbx_datacontainer.items_list == [] zbx_datacontainer.add(DATA[data_type]) assert len(zbx_datacontainer.items_list) == 4 assert zbx_datacontainer.dryrun is True assert zbx_datacontainer.debug_level < 4 ''' Send data to zabbix ''' srv_success, srv_failure, processed, failed, total, time = zbx_datacontainer.send() assert srv_success == 0 assert srv_failure == 0 assert processed == 0 assert failed == 0 assert total == 4 assert zbx_datacontainer.items_list == [] @pytest.mark.parametrize('data_type', pytest_params) def test_debug_yes_dryrun_yes(data_type): """ debug_level to True dryrun to True """ zbx_datacontainer = protobix.DataContainer() zbx_datacontainer.data_type = data_type zbx_datacontainer.dryrun = True zbx_datacontainer.debug_level = 4 assert zbx_datacontainer.items_list == [] zbx_datacontainer.add(DATA[data_type]) assert len(zbx_datacontainer.items_list) == 4 ''' Send data to zabbix ''' srv_success, srv_failure, processed, failed, total, time = zbx_datacontainer.send() assert srv_success == 0 assert srv_failure == 0 assert processed == 0 assert failed == 0 assert total == 4 assert zbx_datacontainer.items_list == [] @pytest.mark.parametrize('data_type', pytest_params) def test_debug_no_dryrun_no(data_type): """ debug_level to False dryrun to False """ zbx_datacontainer = protobix.DataContainer() # Force a Zabbix port so that test fails even if backend is present zbx_datacontainer.server_port = 10060 zbx_datacontainer.data_type = data_type assert zbx_datacontainer.items_list == [] zbx_datacontainer.add(DATA[data_type]) assert len(zbx_datacontainer.items_list) == 4 assert zbx_datacontainer.dryrun is False assert zbx_datacontainer.debug_level < 4 ''' Send data to zabbix ''' with pytest.raises(socket.error): results_list = zbx_datacontainer.send() @pytest.mark.parametrize('data_type', pytest_params) def test_debug_yes_dryrun_no(data_type): """ debug_level to True dryrun to False """ zbx_datacontainer = protobix.DataContainer() zbx_datacontainer.debug_level = 4 # Force a Zabbix port so that test fails even if backend is present zbx_datacontainer.server_port = 10060 zbx_datacontainer.data_type = data_type assert zbx_datacontainer.items_list == [] zbx_datacontainer.add(DATA[data_type]) assert len(zbx_datacontainer.items_list) == 4 assert zbx_datacontainer.dryrun is False assert zbx_datacontainer.debug_level >= 4 ''' Send data to zabbix ''' with pytest.raises(socket.error): results_list = zbx_datacontainer.send() @pytest.mark.parametrize('data_type', pytest_params) def test_server_connection_fails(data_type): """ Connection to Zabbix Server fails """ zbx_datacontainer = protobix.DataContainer() zbx_datacontainer.server_port = 10060 zbx_datacontainer.data_type = data_type assert zbx_datacontainer.items_list == [] assert zbx_datacontainer.server_port == 10060 zbx_datacontainer.add(DATA[data_type]) with pytest.raises(IOError): zbx_datacontainer.send() assert zbx_datacontainer.items_list == [] @pytest.mark.parametrize('data_type', pytest_params) def test_need_backend_debug_no_dryrun_no(data_type): """ debug_level to False dryrun to False """ zbx_datacontainer = protobix.DataContainer() zbx_datacontainer.data_type = data_type assert zbx_datacontainer.items_list == [] zbx_datacontainer.add(DATA[data_type]) assert len(zbx_datacontainer.items_list) == 4 assert zbx_datacontainer.dryrun is False assert zbx_datacontainer.debug_level < 4 ''' Send data to zabbix ''' srv_success, srv_failure, processed, failed, total, time = zbx_datacontainer.send() assert srv_success == 1 assert srv_failure == 0 assert processed == 4 assert failed == 0 assert total == 4 assert zbx_datacontainer.items_list == [] @pytest.mark.parametrize('data_type', pytest_params) def test_need_backend_debug_yes_dryrun_no(data_type): """ debug_level to True dryrun to False """ zbx_datacontainer = protobix.DataContainer() zbx_datacontainer.debug_level = 4 zbx_datacontainer.data_type = data_type assert zbx_datacontainer.items_list == [] zbx_datacontainer.add(DATA[data_type]) assert len(zbx_datacontainer.items_list) == 4 assert zbx_datacontainer.dryrun is False assert zbx_datacontainer.debug_level >= 4 ''' Send data to zabbix ''' srv_success, srv_failure, processed, failed, total, time = zbx_datacontainer.send() assert srv_success == 4 assert srv_failure == 0 assert processed == 4 assert failed == 0 assert total == 4 assert zbx_datacontainer.items_list == [] @pytest.mark.parametrize('data_type', pytest_params) def test_need_backend_debug_yes_dryrun_no(data_type): """ debug_level to True dryrun to False """ zbx_datacontainer = protobix.DataContainer() zbx_datacontainer.debug_level = 4 zbx_datacontainer.data_type = data_type assert zbx_datacontainer.items_list == [] zbx_datacontainer.add(DATA[data_type]) assert len(zbx_datacontainer.items_list) == 4 assert zbx_datacontainer.dryrun is False assert zbx_datacontainer.debug_level >= 4 ''' Send data to zabbix ''' srv_success, srv_failure, processed, failed, total, time = zbx_datacontainer.send() assert srv_success == 4 assert srv_failure == 0 assert processed == 4 assert failed == 0 assert total == 4 assert zbx_datacontainer.items_list == [] python-protobix-1.0.1/tests/test_memory_leak.py000066400000000000000000000073041321121460600217550ustar00rootroot00000000000000""" Test long running process & detect memory leak """ import configobj import pytest import mock import unittest import resource import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) import protobix PAYLOAD = { "items": { "protobix.host1": { "my.protobix.item.int": 0, "my.protobix.item.string": 1 }, "protobix.host2": { "my.protobix.item.int": 0, "my.protobix.item.string": 1 }, "protobix.host3": { "my.protobix.item.int": 0, "my.protobix.item.string": 1 }, "protobix.host4": { "my.protobix.item.int": 0, "my.protobix.item.string": 1 }, "protobix.host5": { "my.protobix.item.int": 0, "my.protobix.item.string": 1 }, "protobix.host6": { "my.protobix.item.int": 0, "my.protobix.item.string": 1 }, "protobix.host7": { "my.protobix.item.int": 0, "my.protobix.item.string": 1 }, "protobix.host8": { "my.protobix.item.int": 0, "my.protobix.item.string": 1 } }, "lld": { 'protobix.host1': { 'my.protobix.lld_item1': [ { '{#PBX_LLD_KEY11}': 0, '{#PBX_LLD_KEY12}': 'lld string' }, { '{#PBX_LLD_KEY11}': 1, '{#PBX_LLD_KEY12}': 'another lld string' } ], 'my.protobix.lld_item2': [ { '{#PBX_LLD_KEY21}': 10, '{#PBX_LLD_KEY21}': 'yet an lld string' }, { '{#PBX_LLD_KEY21}': 2, '{#PBX_LLD_KEY21}': 'yet another lld string' } ] }, 'protobix.host2': { 'my.protobix.lld_item1': [ { '{#PBX_LLD_KEY11}': 0, '{#PBX_LLD_KEY12}': 'lld string' }, { '{#PBX_LLD_KEY11}': 1, '{#PBX_LLD_KEY12}': 'another lld string' } ], 'my.protobix.lld_item2': [ { '{#PBX_LLD_KEY21}': 10, '{#PBX_LLD_KEY21}': 'yet an lld string' }, { '{#PBX_LLD_KEY21}': 2, '{#PBX_LLD_KEY21}': 'yet another lld string' } ] } } } def long_run(data_type, debug_level): """ Generic long running process simulator Used by tests below """ zbx_container = protobix.DataContainer() zbx_container.debug_level = debug_level run=1 max_run=1000 while run <= max_run: zbx_container.data_type = data_type zbx_container.add(PAYLOAD[data_type]) try: zbx_container.send() except: pass if run % (max_run/10) == 0 or run <=1: usage=resource.getrusage(resource.RUSAGE_SELF) display_memory = usage[2]*resource.getpagesize()/1000000.0 if run == 1: initial_memory = usage[2] display_initial_memory = usage[2]*resource.getpagesize()/1000000.0 final_memory = usage[2] print ('Run %i: ru_maxrss=%f mb - initial=%f mb' % ( run, (display_memory), display_initial_memory )) run += 1 return initial_memory, final_memory memory_leak_matrix = ( ('items', 2), ('items', 4), ('lld', 2), ('lld', 4) ) @pytest.mark.parametrize(('data_type','debug_level'), memory_leak_matrix) def test_long_run_for_memory_leak(data_type, debug_level): """ Simulate long running process with and without debug and control memory usage """ initial_memory, final_memory = long_run(data_type, debug_level) assert initial_memory == final_memory python-protobix-1.0.1/tests/test_sampleprobe.py000066400000000000000000000544541321121460600217720ustar00rootroot00000000000000""" Test Protobix sampleprobe """ import configobj import pytest import mock import unittest import socket import resource import time import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) import protobix import logging import argparse # Zabbix force TLSv1.2 protocol # in src/libs/zbxcrypto/tls.c function zbx_tls_init_child HAVE_DECENT_SSL = False if sys.version_info > (2,7,9): import ssl HAVE_DECENT_SSL = True class ProtobixTestProbe(protobix.SampleProbe): __version__="1.0.1" def _get_metrics(self): return { "protobix.host1": { "my.protobix.item.int": 0, "my.protobix.item.string": "item string" }, "protobix.host2": { "my.protobix.item.int": 0, "my.protobix.item.string": "item string" } } def _get_discovery(self): return { 'protobix.host1': { 'my.protobix.lld_item1': [ { '{#PBX_LLD_KEY11}': 0, '{#PBX_LLD_KEY12}': 'lld string' }, { '{#PBX_LLD_KEY11}': 1, '{#PBX_LLD_KEY12}': 'another lld string' } ], 'my.protobix.lld_item2': [ { '{#PBX_LLD_KEY21}': 10, '{#PBX_LLD_KEY21}': 'yet an lld string' }, { '{#PBX_LLD_KEY21}': 2, '{#PBX_LLD_KEY21}': 'yet another lld string' } ] }, 'protobix.host2': { 'my.protobix.lld_item1': [ { '{#PBX_LLD_KEY11}': 0, '{#PBX_LLD_KEY12}': 'lld string' }, { '{#PBX_LLD_KEY11}': 1, '{#PBX_LLD_KEY12}': 'another lld string' } ], 'my.protobix.lld_item2': [ { '{#PBX_LLD_KEY21}': 10, '{#PBX_LLD_KEY21}': 'yet an lld string' }, { '{#PBX_LLD_KEY21}': 2, '{#PBX_LLD_KEY21}': 'yet another lld string' } ] } } class ProtobixTLSTestProbe(ProtobixTestProbe): def run(self, options=None): # Init logging with default values since we don't have real config yet self._init_logging() # Parse command line options args = sys.argv[1:] if isinstance(options, list): args = options self.options = self._parse_args(args) # Get configuration self.zbx_config = self._init_config() # Update logger with configuration self._setup_logging( self.zbx_config.log_type, self.zbx_config.debug_level, self.zbx_config.log_file ) # Datacontainer init zbx_container = protobix.DataContainer( config = self.zbx_config, logger=self.logger ) # Get back hostname from ZabbixAgentConfig self.hostname = self.zbx_config.hostname # Step 1: read probe configuration # initialize any needed object or connection self._init_probe() # Step 2: get data data = {} if self.options.probe_mode == "update": zbx_container.data_type = 'items' data = self._get_metrics() elif self.options.probe_mode == "discovery": zbx_container.data_type = 'lld' data = self._get_discovery() # Step 3: add data to container zbx_container.add(data) # Step 4: send data to Zabbix server server_success, server_failure, processed, failed, total, time = zbx_container.send() return server_success, server_failure, processed, failed, total, time class ProtobixTestProbe2(protobix.SampleProbe): __version__="1.0.1" """ Check default configuration of the sample probe """ def test_default_configuration(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args([]) assert pbx_test_probe.options.config_file is None assert pbx_test_probe.options.debug_level is None assert pbx_test_probe.options.discovery is False assert pbx_test_probe.options.dryrun is False assert pbx_test_probe.options.update is False assert pbx_test_probe.options.server_port is None assert pbx_test_probe.options.server_active is None """ Check --update-items argument """ def test_command_line_option_update_items(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--update-items']) pbx_config = pbx_test_probe._init_config() assert pbx_test_probe.options.discovery is False assert pbx_test_probe.options.update is True assert pbx_test_probe.options.probe_mode == 'update' """ Check --discovery argument """ def test_command_line_option_discovery(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--discovery']) pbx_config = pbx_test_probe._init_config() assert pbx_test_probe.options.discovery is True assert pbx_test_probe.options.update is False assert pbx_test_probe.options.probe_mode == 'discovery' """ Check exception when providing both --update-items & --discovery arguments """ def test_force_both_discovery_and_update(): pbx_test_probe = ProtobixTestProbe() with pytest.raises(ValueError): result = pbx_test_probe.run(['--discovery', '--update-items']) """ Check -v argument. Used to set logger log level """ def test_force_verbosity(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['-vvvv']) pbx_config = pbx_test_probe._init_config() assert pbx_test_probe.options.debug_level == 4 pbx_test_probe.options = pbx_test_probe._parse_args(['-vv']) pbx_config = pbx_test_probe._init_config() assert pbx_test_probe.options.debug_level == 2 pbx_test_probe.options = pbx_test_probe._parse_args(['-vvvvvvvvv']) assert pbx_test_probe.options.debug_level == 9 pbx_config = pbx_test_probe._init_config() assert pbx_config.debug_level == 4 """ Check -d & --dryrun argument. """ def test_force_dryrun(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--dryrun']) pbx_config = pbx_test_probe._init_config() assert pbx_test_probe.options.dryrun is True pbx_test_probe.options = pbx_test_probe._parse_args(['-d']) pbx_config = pbx_test_probe._init_config() assert pbx_test_probe.options.dryrun is True """ Check -z & --zabbix-server argument. """ def test_command_line_option_zabbix_server(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--zabbix-server', '192.168.0.1']) pbx_config = pbx_test_probe._init_config() assert pbx_config.server_active == '192.168.0.1' pbx_test_probe.options = pbx_test_probe._parse_args(['-z', '192.168.0.2']) pbx_config = pbx_test_probe._init_config() assert pbx_config.server_active == '192.168.0.2' """ Check -p & --port argument. """ def test_command_line_option_port(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--port', '10052']) pbx_config = pbx_test_probe._init_config() assert pbx_config.server_port == 10052 pbx_test_probe.options = pbx_test_probe._parse_args(['-p', '10060']) pbx_config = pbx_test_probe._init_config() assert pbx_config.server_port == 10060 """ Check --tls-cert-file argument. """ def test_command_line_option_tls_cert_file(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-cert-file', '/tmp/test_file.crt']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_cert_file == '/tmp/test_file.crt' """ Check --tls-key-file argument. """ def test_command_line_option_tls_key_file(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-key-file', '/tmp/test_file.key']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_key_file == '/tmp/test_file.key' """ Check --tls-ca-file argument. """ def test_command_line_option_tls_ca_file(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-ca-file', '/tmp/test_ca_file.crt']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_ca_file == '/tmp/test_ca_file.crt' """ Check --tls-crl-file argument. """ def test_command_line_option_tls_crl_file(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-crl-file', '/tmp/test_file.crl']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_crl_file == '/tmp/test_file.crl' """ Check --tls-psk-file argument. """ def test_command_line_option_tls_psk_file(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-psk-file', '/tmp/test_file.psk']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_psk_file == '/tmp/test_file.psk' """ Check --tls-psk-identity argument. """ def test_command_line_option_tls_psk_identity(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-psk-identity', 'Zabbix TLS/PSK identity']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_psk_identity == 'Zabbix TLS/PSK identity' """ Check --tls-server-cert-issuer argument. """ def test_command_line_option_tls_server_cert_issuer(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-server-cert-issuer', 'Zabbix TLS cert issuer']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_server_cert_issuer == 'Zabbix TLS cert issuer' """ Check --tls-server-cert-subject argument. """ def test_command_line_option_tls_server_cert_subject(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-server-cert-subject', 'Zabbix TLS cert subject']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_server_cert_subject == 'Zabbix TLS cert subject' """ Check --tls-connect argument. """ def test_command_line_option_tls_connect(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-connect', 'cert']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_connect == 'cert' pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-connect', 'psk']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_connect == 'psk' pbx_test_probe.options = pbx_test_probe._parse_args(['--tls-connect', 'unencrypted']) pbx_config = pbx_test_probe._init_config() assert pbx_config.tls_connect == 'unencrypted' """ Check logger configuration in console mode """ def test_log_console(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe._init_logging() assert isinstance(pbx_test_probe.logger, logging.Logger) pbx_test_probe._setup_logging('console', 4, '/tmp/log_file') assert len(pbx_test_probe.logger.handlers) == 1 assert pbx_test_probe.logger.level == logging.DEBUG assert isinstance(pbx_test_probe.logger.handlers[0], logging.StreamHandler) """ Check logger configuration in file mode & debug """ def test_log_file(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe._init_logging() assert isinstance(pbx_test_probe.logger, logging.Logger) pbx_test_probe._setup_logging('file', 4, '/tmp/log_file') assert len(pbx_test_probe.logger.handlers) == 1 assert pbx_test_probe.logger.level == logging.DEBUG assert isinstance(pbx_test_probe.logger.handlers[0], logging.FileHandler) """ Check logger configuration in file mode with invalid file Here, invalid means that it doesn't exists, or we don't have permission to write into """ def test_log_file_invalid(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe._init_logging() assert isinstance(pbx_test_probe.logger, logging.Logger) with pytest.raises(IOError): pbx_test_probe._setup_logging('file', 4, '/do_not_have_permission') assert pbx_test_probe.logger.level == logging.NOTSET assert len(pbx_test_probe.logger.handlers) == 0 """ Check logger configuration in system (syslog) mode """ def test_log_syslog(): pbx_test_probe = ProtobixTestProbe() pbx_test_probe._init_logging() assert isinstance(pbx_test_probe.logger, logging.Logger) pbx_test_probe._setup_logging('system', 3, None) assert len(pbx_test_probe.logger.handlers) == 1 assert pbx_test_probe.logger.level == logging.INFO assert isinstance(pbx_test_probe.logger.handlers[0], logging.handlers.SysLogHandler) """ Check a custom probe without _get_metrics method. """ def test_not_implemented_get_metrics(): pbx_test_probe = ProtobixTestProbe2() with pytest.raises(NotImplementedError): pbx_test_probe.run([]) """ Check a custom probe without _get_discovery method. """ def test_not_implemented_get_discovery(): pbx_test_probe = ProtobixTestProbe2() with pytest.raises(NotImplementedError): pbx_test_probe.run(['--discovery']) """ Check that sample probe correctly catches exception from _init_probe """ def test_init_probe_exception(): pbx_test_probe = ProtobixTestProbe2() with mock.patch('protobix.SampleProbe._init_probe') as mock_init_probe: mock_init_probe.side_effect = Exception('Something went wrong') result = pbx_test_probe.run([]) assert result == 1 """ Check that sample probe correctly catches exception from _get_metrics """ def test_get_metrics_exception(): pbx_test_probe = ProtobixTestProbe2() with mock.patch('protobix.SampleProbe._get_metrics') as mock_get_metrics: mock_get_metrics.side_effect = Exception('Something went wrong in _get_metrics') result = pbx_test_probe.run([]) assert result == 2 """ Check that sample probe correctly catches exception from _get_discovery """ def test_get_discovery_exception(): pbx_test_probe = ProtobixTestProbe2() with mock.patch('protobix.SampleProbe._get_discovery') as mock_get_discovery: mock_get_discovery.side_effect = Exception('Something went wrong in _get_discovery') result = pbx_test_probe.run(['--discovery']) assert result == 2 """ Check that sample probe correctly catches exception from DataContainer add method """ def test_datacontainer_add_exception(): pbx_test_probe = ProtobixTestProbe() with mock.patch('protobix.DataContainer.add') as mock_datacontainer_add: mock_datacontainer_add.side_effect = Exception('Something went wrong in DataContainer.add') result = pbx_test_probe.run([]) assert result == 3 """ Check that sample probe correctly catches exception from DataContainer send method """ def test_datacontainer_send_exception(): pbx_test_probe = ProtobixTestProbe() with mock.patch('protobix.DataContainer.send') as mock_datacontainer_send: mock_datacontainer_send.side_effect = Exception('Another something went wrong') result = pbx_test_probe.run([]) assert result == 4 """ Check that sample probe correctly catches socket exception from DataContainer send method """ def test_datacontainer_send_socket_error(): pbx_test_probe = ProtobixTestProbe() with mock.patch('protobix.DataContainer.send') as mock_datacontainer_send: mock_datacontainer_send.side_effect = socket.error result = pbx_test_probe.run([]) assert result == 4 """ Check return 0 when everything is fine """ def test_everything_runs_fine(): pbx_test_probe = ProtobixTestProbe() with mock.patch('protobix.DataContainer.send') as mock_datacontainer_send: mock_datacontainer_send.side_effect = None result = pbx_test_probe.run([]) assert result == 0 if HAVE_DECENT_SSL is True: """ Check sending data with or without TLS with debug disabled """ pytest_matrix = ( ('items', False, False), ('lld', False, False), ('items', True, False), ('lld', True, False), ('items', False, True), ('lld', False, True), ('items', True, True), ('lld', True, True), ) @pytest.mark.parametrize('data_type,tls_enabled,tls_crl_enabled', pytest_matrix) def test_need_backend_tls_cert(data_type, tls_enabled, tls_crl_enabled): params = [] if tls_enabled: params = [ '--tls-connect', 'cert', '--tls-ca-file', 'tests/tls_ca/rogue-protobix-ca.cert.pem', '--tls-cert-file', 'tests/tls_ca/rogue-protobix-client.cert.pem', '--tls-key-file', 'tests/tls_ca/rogue-protobix-client.key.pem', ] if tls_crl_enabled: params.append('--tls-crl-file') params.append('tests/tls_ca/rogue-protobix.crl') params.append('--update' if data_type == 'items' else '--discovery') params.append('-vvv') pbx_test_probe = ProtobixTLSTestProbe() server_success, server_failure, processed, failed, total, time = pbx_test_probe.run(params) if tls_enabled is False: assert server_success == 1 assert server_failure == 0 assert processed == 4 assert failed == 0 assert total == 4 else: # protobix.host1 does NOT have TLS enabled # therefore items sent on behalf of protobix.host1 must fail assert server_success == 1 assert server_failure == 0 assert processed == 2 assert failed == 2 assert total == 4 """ Check sending data with or without TLS with debug enabled """ pytest_matrix = ( ('items', False, False), ('lld', False, False), ('items', True, False), ('lld', True, False), ('items', False, True), ('lld', False, True), ('items', True, True), ('lld', True, True), ) @pytest.mark.parametrize('data_type,tls_enabled,tls_crl_enabled', pytest_matrix) def test_need_backend_tls_cert_debug(data_type, tls_enabled, tls_crl_enabled): params = [] if tls_enabled: params = [ '--tls-connect', 'cert', '--tls-ca-file', 'tests/tls_ca/rogue-protobix-ca.cert.pem', '--tls-cert-file', 'tests/tls_ca/rogue-protobix-client.cert.pem', '--tls-key-file', 'tests/tls_ca/rogue-protobix-client.key.pem', ] if tls_crl_enabled: params.append('--tls-crl-file') params.append('tests/tls_ca/rogue-protobix.crl') params.append('--update' if data_type == 'items' else '--discovery') params.append('-vvvvv') pbx_test_probe = ProtobixTLSTestProbe() server_success, server_failure, processed, failed, total, time = pbx_test_probe.run(params) if tls_enabled is False: assert server_success == 4 assert server_failure == 0 assert processed == 4 assert failed == 0 assert total == 4 else: # protobix.host1 does NOT have TLS enabled # therefore items sent on behalf of protobix.host1 must fail assert server_success == 4 assert server_failure == 0 assert processed == 2 assert failed == 2 assert total == 4 """ Check sending data with or without TLS with debug disabled """ pytest_matrix = ( ('items', False, False), ('lld', False, False), ('items', True, False), ('lld', True, False), ('items', False, True), ('lld', False, True), ('items', True, True), ('lld', True, True), ) @pytest.mark.parametrize('data_type,tls_enabled,tls_crl_enabled', pytest_matrix) def test_need_backend_tls_cert_invalid(data_type, tls_enabled, tls_crl_enabled): params = [] if tls_enabled: params = [ '--tls-connect', 'cert', '--tls-ca-file', 'tests/tls_ca/protobix-ca.cert.pem', '--tls-cert-file', 'tests/tls_ca/protobix-client.cert.pem', '--tls-key-file', 'tests/tls_ca/protobix-client.key.pem', ] if tls_crl_enabled: params.append('--tls-crl-file') params.append('tests/tls_ca/protobix.crl') params.append('--update' if data_type == 'items' else '--discovery') params.append('-vvv') pbx_test_probe = ProtobixTLSTestProbe() if tls_enabled is True: with pytest.raises(ssl.SSLError) as err: pbx_test_probe.run(params) else: server_success, server_failure, processed, failed, total, time = pbx_test_probe.run(params) assert server_success == 1 assert server_failure == 0 assert processed == 4 assert failed == 0 assert total == 4 """ Check sending data with or without TLS with debug enabled """ pytest_matrix = ( ('items', False, False), ('lld', False, False), ('items', True, False), ('lld', True, False), ('items', False, True), ('lld', False, True), ('items', True, True), ('lld', True, True), ) @pytest.mark.parametrize('data_type,tls_enabled,tls_crl_enabled', pytest_matrix) def test_need_backend_tls_cert_invalid_debug(data_type, tls_enabled, tls_crl_enabled): params = [] if tls_enabled: params = [ '--tls-connect', 'cert', '--tls-ca-file', 'tests/tls_ca/protobix-ca.cert.pem', '--tls-cert-file', 'tests/tls_ca/protobix-client.cert.pem', '--tls-key-file', 'tests/tls_ca/protobix-client.key.pem', ] if tls_crl_enabled: params.append('--tls-crl-file') params.append('tests/tls_ca/protobix.crl') params.append('--update' if data_type == 'items' else '--discovery') params.append('-vvvvv') pbx_test_probe = ProtobixTLSTestProbe() if tls_enabled is True: with pytest.raises(ssl.SSLError) as err: pbx_test_probe.run(params) else: server_success, server_failure, processed, failed, total, time = pbx_test_probe.run(params) assert server_success == 4 assert server_failure == 0 assert processed == 4 assert failed == 0 assert total == 4 python-protobix-1.0.1/tests/test_senderprotocol.py000066400000000000000000000255471321121460600225240ustar00rootroot00000000000000""" Tests for protobix.SenderProtocol """ import configobj import pytest import mock import unittest import time try: import simplejson as json except ImportError: import json import socket import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) import protobix try: import simplejson as json except ImportError: import json import struct if sys.version_info < (3,): def b(x): return x else: import codecs def b(x): return codecs.utf_8_encode(x)[0] # Zabbix force TLSv1.2 protocol # in src/libs/zbxcrypto/tls.c function zbx_tls_init_child HAVE_DECENT_SSL = False if sys.version_info > (2,7,9): import ssl HAVE_DECENT_SSL = True def test_default_params(): """ Default configuration """ zbx_senderprotocol = protobix.SenderProtocol() assert zbx_senderprotocol.server_active == '127.0.0.1' assert zbx_senderprotocol.server_port == 10051 assert zbx_senderprotocol._config.dryrun is False assert zbx_senderprotocol.items_list == [] def test_server_active_custom(): """ Test setting zbx_server with custom value """ zbx_senderprotocol = protobix.SenderProtocol() assert zbx_senderprotocol.server_active == '127.0.0.1' zbx_senderprotocol.server_active = 'myserver.domain.tld' assert zbx_senderprotocol.server_active == 'myserver.domain.tld' def test_server_port_custom(): """ Test setting server_port with custom value """ zbx_senderprotocol = protobix.SenderProtocol() assert zbx_senderprotocol.server_port == 10051 zbx_senderprotocol.server_port = 10052 assert zbx_senderprotocol.server_port == 10052 def test_server_port_invalid_greater_than_32767(): """ Test setting server_port with invalid value """ zbx_senderprotocol = protobix.SenderProtocol() with pytest.raises(ValueError) as err: zbx_senderprotocol.server_port = 40000 assert str(err.value) == 'ServerPort must be between 1024 and 32767' assert zbx_senderprotocol.server_port == 10051 def test_server_port_invalid_lower_than_1024(): """ Test setting server_port with invalid value """ zbx_senderprotocol = protobix.SenderProtocol() with pytest.raises(ValueError) as err: zbx_senderprotocol.server_port = 1000 assert str(err.value) == 'ServerPort must be between 1024 and 32767' assert zbx_senderprotocol.server_port == 10051 def test_debug_custom(): """ Test setting server_port with custom value """ zbx_senderprotocol = protobix.SenderProtocol() assert zbx_senderprotocol.debug_level == 3 zbx_senderprotocol.debug_level = 4 assert zbx_senderprotocol.debug_level == 4 def test_debug_invalid_lower_than_0(): """ Test setting server_port with invalid value """ zbx_senderprotocol = protobix.SenderProtocol() with pytest.raises(ValueError) as err: zbx_senderprotocol.debug_level = -1 assert str(err.value) == 'DebugLevel must be between 0 and 5, -1 provided' assert zbx_senderprotocol.debug_level == 3 def test_debug_invalid_greater_than_5(): """ Test setting server_port with invalid value """ zbx_senderprotocol = protobix.SenderProtocol() with pytest.raises(ValueError) as err: zbx_senderprotocol.debug_level = 10 assert str(err.value) == 'DebugLevel must be between 0 and 5, 10 provided' assert zbx_senderprotocol.debug_level == 3 def test_dryrun_custom(): """ Test setting dryrun with custom value """ zbx_senderprotocol = protobix.SenderProtocol() assert zbx_senderprotocol._config.dryrun is False zbx_senderprotocol._config.dryrun = True assert zbx_senderprotocol._config.dryrun is True zbx_senderprotocol._config.dryrun = False assert zbx_senderprotocol._config.dryrun is False def test_dryrun_invalid(): """ Test setting dryrun with invalid value """ zbx_senderprotocol = protobix.SenderProtocol() assert zbx_senderprotocol._config.dryrun is False with pytest.raises(ValueError) as err: zbx_senderprotocol._config.dryrun = 'invalid' assert str(err.value) == 'dryrun parameter requires boolean' assert zbx_senderprotocol._config.dryrun is False def test_clock_integer(): """ Test clock method """ zbx_senderprotocol = protobix.SenderProtocol() assert isinstance(zbx_senderprotocol.clock, int) is True def test_clock_accurate(): """ Test clock method """ zbx_senderprotocol = protobix.SenderProtocol() assert zbx_senderprotocol.clock == int(time.time()) @mock.patch('socket.socket', return_value=mock.MagicMock(name='socket', spec=socket.socket)) def test_send_to_zabbix(mock_socket): """ Test sending data to Zabbix Server """ item = { 'host': 'myhostname', 'key': 'my.item.key', 'value': 1, 'clock': int(time.time())} payload = json.dumps({ "data": [item], "request": "sender data", "clock": int(time.time()) }) packet = b('ZBXD\1') + struct.pack('= 2.2 'processed: 1; failed: 2; total: 3; seconds spent: 0.123456', ) @pytest.mark.parametrize('zabbix_answer', zabbix_answer_params) def test_handle_response(zabbix_answer): """ Test Zabbix Server/Proxy answer """ payload='{"response":"success","info":"'+zabbix_answer+'"}' zbx_datacontainer = protobix.DataContainer() srv_response, processed, failed, total, time = zbx_datacontainer._handle_response(payload) assert srv_response == 'success' assert processed == 1 assert failed == 2 assert total == 3 assert time == 0.123456 zabbix_answer_params= ( # Zabbix Sender protocol <= 2.0 'Invalid content', # Zabbix Sender protocol >= 2.2 'invalid content', ) @pytest.mark.parametrize('zabbix_answer', zabbix_answer_params) def test_handle_response_with_invalid_content(zabbix_answer): """ Test Zabbix Server/Proxy answer """ payload='{"response":"success","info":"'+zabbix_answer+'"}' zbx_datacontainer = protobix.DataContainer() with pytest.raises(IndexError): zbx_datacontainer._handle_response(payload) @mock.patch('socket.socket', return_value=mock.MagicMock(name='socket', spec=socket.socket)) def test_read_from_zabbix_valid_content(mock_socket): """ Test sending data to Zabbix Server """ answer_payload = '{"info": "processed: 0; failed: 1; total: 1; seconds spent: 0.000441", "response": "success"}' answer_packet = b('ZBXD\1') + struct.pack('