Net-Prometheus-0.07000755001750001750 013362133440 13037 5ustar00leoleo000000000000Net-Prometheus-0.07/Build.PL000444001750001750 104513362133440 14470 0ustar00leoleo000000000000use strict; use warnings; use Module::Build; my $build = Module::Build->new( module_name => 'Net::Prometheus', configure_requires => { 'Module::Build' => '0.4004', # test_requires }, requires => { 'List::Util' => '1.33', 'Ref::Util' => 0, 'Struct::Dumb' => 0, }, test_requires => { 'List::Util' => '1.29', # pairgrep 'Test::Fatal' => 0, 'Test::More' => '0.88', # done_testing }, license => 'perl', create_license => 1, create_readme => 1, ); $build->create_build_script; Net-Prometheus-0.07/Changes000444001750001750 405413362133440 14472 0ustar00leoleo000000000000Revision history for Net-Prometheus 0.07 2018-10-18 16:52:17 [CHANGES] * Escape embedded characters in HELP text * Add `version` and `charset` to Content-Type HTTP header * Docs fix: histogram buckets limits are upper, not lower bounds 0.06 2018-10-05 13:52:41 [CHANGES] * Allow $metric->labels to take a single HASH reference as alternative to ordered list of strings [BUGFIXES] * Fix autovivification of gauge functions with labels (RT127284) * Spelling fixes from Debian (RT120491) * Make sure that ->unregister actually does so 0.05 2016/10/28 20:56:35 [CHANGES] * Allow setting name prefix and extra labels on a process exporter * Implement process scraping of other PIDs in the Linux collector [BUGFIXES] * Prometheus needs all the labelsets of every variable grouped together; so rearrange the ->collect results 0.04 2016/10/27 16:10:06 [CHANGES] * Implement a process collector for Linux * By default, attempt to load a process collector at construction time * Various documentation fixes [BUGFIXES] * Compatibility for perl 5.8.x by avoiding the "//" operator 0.03 2016/10/26 18:23:27 [CHANGES] * Implement Histogram metrics * Allow value-returing callback functions on Gauges * Added Metric Groups * Document the register/unregister methods and the Collector interface 0.02 2016/10/26 00:30:25 [CHANGES] * Many internal structure changes to support new features + Exposed $metric->samples as a documented method + Created Sample and MetricSamples types + Prepare for true multimetric collectors * Basic validation on metric/label names and values [BUGFIXES] * Ensure that label values with embedded NULs render correctly 0.01 2016/10/24 18:40:03 First version, released on an unsuspecting world. Net-Prometheus-0.07/LICENSE000444001750001750 4376213362133440 14235 0ustar00leoleo000000000000This software is copyright (c) 2018 by Paul Evans . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2018 by Paul Evans . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: 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 humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy 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 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2018 by Paul Evans . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Net-Prometheus-0.07/MANIFEST000444001750001750 117613362133440 14332 0ustar00leoleo000000000000Build.PL Changes examples/parent-process.psgi examples/static.psgi lib/Net/Prometheus.pm lib/Net/Prometheus/Counter.pm lib/Net/Prometheus/Gauge.pm lib/Net/Prometheus/Histogram.pm lib/Net/Prometheus/Metric.pm lib/Net/Prometheus/ProcessCollector.pm lib/Net/Prometheus/ProcessCollector/linux.pm lib/Net/Prometheus/Summary.pm lib/Net/Prometheus/Types.pm LICENSE MANIFEST This list of files META.json META.yml README t/00use.t t/01metric.t t/02labels.t t/10gauge.t t/11counter.t t/12summary.t t/13histogram.t t/20client.t t/21label-rendering.t t/22metric-grouping.t t/30psgi.t t/40process-collector.t t/41process-collector-linux.t t/99pod.t Net-Prometheus-0.07/META.json000444001750001750 425613362133440 14624 0ustar00leoleo000000000000{ "abstract" : "export monitoring metrics for F", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4224", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Net-Prometheus", "prereqs" : { "configure" : { "requires" : { "Module::Build" : "0.4004" } }, "runtime" : { "requires" : { "List::Util" : "1.33", "Ref::Util" : "0", "Struct::Dumb" : "0" } }, "test" : { "requires" : { "List::Util" : "1.29", "Test::Fatal" : "0", "Test::More" : "0.88" } } }, "provides" : { "Net::Prometheus" : { "file" : "lib/Net/Prometheus.pm", "version" : "0.07" }, "Net::Prometheus::Counter" : { "file" : "lib/Net/Prometheus/Counter.pm", "version" : "0.07" }, "Net::Prometheus::Gauge" : { "file" : "lib/Net/Prometheus/Gauge.pm", "version" : "0.07" }, "Net::Prometheus::Histogram" : { "file" : "lib/Net/Prometheus/Histogram.pm", "version" : "0.07" }, "Net::Prometheus::Metric" : { "file" : "lib/Net/Prometheus/Metric.pm", "version" : "0.07" }, "Net::Prometheus::ProcessCollector" : { "file" : "lib/Net/Prometheus/ProcessCollector.pm", "version" : "0.07" }, "Net::Prometheus::ProcessCollector::linux" : { "file" : "lib/Net/Prometheus/ProcessCollector/linux.pm", "version" : "0.07" }, "Net::Prometheus::Summary" : { "file" : "lib/Net/Prometheus/Summary.pm", "version" : "0.07" }, "Net::Prometheus::Types" : { "file" : "lib/Net/Prometheus/Types.pm", "version" : "0.07" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ] }, "version" : "0.07", "x_serialization_backend" : "JSON::PP version 2.97001" } Net-Prometheus-0.07/META.yml000444001750001750 271413362133440 14451 0ustar00leoleo000000000000--- abstract: 'export monitoring metrics for F' author: - 'Paul Evans ' build_requires: List::Util: '1.29' Test::Fatal: '0' Test::More: '0.88' configure_requires: Module::Build: '0.4004' dynamic_config: 1 generated_by: 'Module::Build version 0.4224, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Net-Prometheus provides: Net::Prometheus: file: lib/Net/Prometheus.pm version: '0.07' Net::Prometheus::Counter: file: lib/Net/Prometheus/Counter.pm version: '0.07' Net::Prometheus::Gauge: file: lib/Net/Prometheus/Gauge.pm version: '0.07' Net::Prometheus::Histogram: file: lib/Net/Prometheus/Histogram.pm version: '0.07' Net::Prometheus::Metric: file: lib/Net/Prometheus/Metric.pm version: '0.07' Net::Prometheus::ProcessCollector: file: lib/Net/Prometheus/ProcessCollector.pm version: '0.07' Net::Prometheus::ProcessCollector::linux: file: lib/Net/Prometheus/ProcessCollector/linux.pm version: '0.07' Net::Prometheus::Summary: file: lib/Net/Prometheus/Summary.pm version: '0.07' Net::Prometheus::Types: file: lib/Net/Prometheus/Types.pm version: '0.07' requires: List::Util: '1.33' Ref::Util: '0' Struct::Dumb: '0' resources: license: http://dev.perl.org/licenses/ version: '0.07' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Net-Prometheus-0.07/README000444001750001750 1226713362133440 14104 0ustar00leoleo000000000000NAME Net::Prometheus - export monitoring metrics for prometheus SYNOPSIS use Net::Prometheus; my $client = Net::Prometheus->new; my $counter = $client->new_counter( name => "requests", help => "Number of received requests", ); sub handle_request { $counter->inc; ... } use Plack::Builder; builder { mount "/metrics" => $client->psgi_app; ... } DESCRIPTION This module provides the ability for a program to collect monitoring metrics and export them to the prometheus.io monitoring server. As prometheus will expect to collect the metrics by making an HTTP request, facilities are provided to yield a PSGI application that the containing program can embed in its own structure to provide the results, or the application can generate a plain-text result directly and serve them by its own means. CONSTRUCTOR new $prometheus = Net::Prometheus->new; Returns a new Net::Prometheus instance. Takes the following named arguments: disable_process_collector => BOOL If present and true, this instance will not load the default process collector from Net::Prometheus::ProcessCollector. If absent or false, such a collector will be loaded by default. disable_perl_collector => BOOL If present and true, this instance will not load perl-specific collector from Net::Prometheus::PerlCollector. If absent or false this collector is loaded if the module is installed and useable. These two options are provided for testing purposes, or for specific use-cases where such features are not required. Usually it's best just to leave these enabled. METHODS register $collector = $prometheus->register( $collector ) Registers a new collector to be collected from by the render method. The collector instance itself is returned, for convenience. unregister $prometheus->unregister( $collector ) Removes a previously-registered collector. new_gauge $gauge = $prometheus->new_gauge( %args ) Constructs a new Net::Prometheus::Gauge using the arguments given and registers it with the exporter. The newly-constructed gauge is returned. new_counter $counter = $prometheus->new_counter( %args ) Constructs a new Net::Prometheus::Counter using the arguments given and registers it with the exporter. The newly-constructed counter is returned. new_summary $summary = $prometheus->new_summary( %args ) Constructs a new Net::Prometheus::Summary using the arguments given and registers it with the exporter. The newly-constructed summary is returned. new_histogram $histogram = $prometheus->new_histogram( %args ) Constructs a new Net::Prometheus::Histogram using the arguments given and registers it with the exporter. The newly-constructed histogram is returned. new_metricgroup $group = $prometheus->new_metricgroup( %args ) Returns a new Metric Group instance as a convenience for registering multiple metrics using the same namespace and subsystem arguments. Takes the following named arguments: namespace => STR subsystem => STR String values to pass by default into new metrics the group will construct. Once constructed, the group acts as a proxy to the other new_* methods, passing in these values as overrides. $gauge = $group->new_gauge( ... ) $counter = $group->new_counter( ... ) $summary = $group->new_summary( ... ) $histogram = $group->new_histogram( ... ) collect @metricsamples = $prometheus->collect Returns a list of "MetricSamples" in Net::Prometheus::Types obtained from all of the currently-registered collectors. render $str = $prometheus->render Returns a string in the Prometheus text exposition format containing the current values of all the registered metrics. psgi_app $app = $prometheus->psgi_app Returns a new PSGI application as a CODE reference. This application will render the metrics in the Prometheus text exposition format, suitable for scraping by the Prometheus collector. This application will respond to any GET request, and reject requests for any other method. COLLECTORS The toplevel Net::Prometheus object stores a list of "collector" instances, which are used to generate the values that will be made visible via the "render" method. A collector can be any object instance that has a method called collect, which when invoked is passed no arguments and expected to return a list of "MetricSamples" in Net::Prometheus::Types structures. @metricsamples = $collector->collect The Net::Prometheus::Metric class is already a valid collector (and hence, so too are the individual metric type subclasses). This interface allows the creation of new custom collector objects, that more directly collect information to be exported. TODO * Split Registry out from toplevel instance. * Write some actual example programs. AUTHOR Paul Evans Net-Prometheus-0.07/examples000755001750001750 013362133440 14655 5ustar00leoleo000000000000Net-Prometheus-0.07/examples/parent-process.psgi000555001750001750 52613362133440 20631 0ustar00leoleo000000000000use strict; use warnings; use Net::Prometheus; use Net::Prometheus::ProcessCollector; my $client = Net::Prometheus->new; $client->register( Net::Prometheus::ProcessCollector->new( prefix => "parent_process", pid => getppid(), ) ); use Plack::Builder; builder { mount "/metrics" => $client->psgi_app, sub { [ 500, [], [] ] } }; Net-Prometheus-0.07/examples/static.psgi000555001750001750 41413362133440 17147 0ustar00leoleo000000000000use strict; use warnings; use Net::Prometheus; my $client = Net::Prometheus->new; $client->new_gauge( name => "ten", help => "The number ten", )->set( 10 ); use Plack::Builder; builder { mount "/metrics" => $client->psgi_app, sub { [ 500, [], [] ] } }; Net-Prometheus-0.07/lib000755001750001750 013362133440 13605 5ustar00leoleo000000000000Net-Prometheus-0.07/lib/Net000755001750001750 013362133440 14333 5ustar00leoleo000000000000Net-Prometheus-0.07/lib/Net/Prometheus.pm000444001750001750 2315513362133440 17207 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2016-2018 -- leonerd@leonerd.org.uk package Net::Prometheus; use strict; use warnings; our $VERSION = '0.07'; use Carp; use List::Util 1.29 qw( pairmap ); use Net::Prometheus::Gauge; use Net::Prometheus::Counter; use Net::Prometheus::Summary; use Net::Prometheus::Histogram; use Net::Prometheus::ProcessCollector; use Net::Prometheus::Types qw( MetricSamples ); use constant HAVE_PERLCOLLECTOR => defined eval { require Net::Prometheus::PerlCollector }; =head1 NAME C - export monitoring metrics for F =head1 SYNOPSIS use Net::Prometheus; my $client = Net::Prometheus->new; my $counter = $client->new_counter( name => "requests", help => "Number of received requests", ); sub handle_request { $counter->inc; ... } use Plack::Builder; builder { mount "/metrics" => $client->psgi_app; ... } =head1 DESCRIPTION This module provides the ability for a program to collect monitoring metrics and export them to the F monitoring server. As C will expect to collect the metrics by making an HTTP request, facilities are provided to yield a L application that the containing program can embed in its own structure to provide the results, or the application can generate a plain-text result directly and serve them by its own means. =cut =head1 CONSTRUCTOR =cut =head2 new $prometheus = Net::Prometheus->new; Returns a new C instance. Takes the following named arguments: =over =item disable_process_collector => BOOL If present and true, this instance will not load the default process collector from L. If absent or false, such a collector will be loaded by default. =item disable_perl_collector => BOOL If present and true, this instance will not load perl-specific collector from L. If absent or false this collector is loaded if the module is installed and useable. These two options are provided for testing purposes, or for specific use-cases where such features are not required. Usually it's best just to leave these enabled. =back =cut sub new { my $class = shift; my %args = @_; my $self = bless { collectors => [], }, $class; if( not $args{disable_process_collector} and my $process_collector = Net::Prometheus::ProcessCollector->new ) { $self->register( $process_collector ); } if( not $args{disable_perl_collector} and HAVE_PERLCOLLECTOR ) { $self->register( Net::Prometheus::PerlCollector->new ); } return $self; } =head1 METHODS =cut =head2 register $collector = $prometheus->register( $collector ) Registers a new L to be collected from by the C method. The collector instance itself is returned, for convenience. =cut sub register { my $self = shift; my ( $collector ) = @_; # TODO: ban duplicate registration push @{ $self->{collectors} }, $collector; return $collector; } =head2 unregister $prometheus->unregister( $collector ) Removes a previously-registered collector. =cut sub unregister { my $self = shift; my ( $collector ) = @_; my $found; @{ $self->{collectors} } = grep { not( $_ == $collector and ++$found ) } @{ $self->{collectors} }; $found or croak "No such collector"; } =head2 new_gauge $gauge = $prometheus->new_gauge( %args ) Constructs a new L using the arguments given and registers it with the exporter. The newly-constructed gauge is returned. =cut sub new_gauge { my $self = shift; my %args = @_; return $self->register( Net::Prometheus::Gauge->new( %args ) ); } =head2 new_counter $counter = $prometheus->new_counter( %args ) Constructs a new L using the arguments given and registers it with the exporter. The newly-constructed counter is returned. =cut sub new_counter { my $self = shift; my %args = @_; return $self->register( Net::Prometheus::Counter->new( %args ) ); } =head2 new_summary $summary = $prometheus->new_summary( %args ) Constructs a new L using the arguments given and registers it with the exporter. The newly-constructed summary is returned. =cut sub new_summary { my $self = shift; my %args = @_; return $self->register( Net::Prometheus::Summary->new( %args ) ); } =head2 new_histogram $histogram = $prometheus->new_histogram( %args ) Constructs a new L using the arguments given and registers it with the exporter. The newly-constructed histogram is returned. =cut sub new_histogram { my $self = shift; my %args = @_; return $self->register( Net::Prometheus::Histogram->new( %args ) ); } =head2 new_metricgroup $group = $prometheus->new_metricgroup( %args ) Returns a new Metric Group instance as a convenience for registering multiple metrics using the same C and C arguments. Takes the following named arguments: =over =item namespace => STR =item subsystem => STR String values to pass by default into new metrics the group will construct. =back Once constructed, the group acts as a proxy to the other C methods, passing in these values as overrides. $gauge = $group->new_gauge( ... ) $counter = $group->new_counter( ... ) $summary = $group->new_summary( ... ) $histogram = $group->new_histogram( ... ) =cut sub new_metricgroup { my $self = shift; my ( %args ) = @_; return Net::Prometheus::_MetricGroup->new( $self, %args ); } =head2 collect @metricsamples = $prometheus->collect Returns a list of L obtained from all of the currently-registered collectors. =cut sub collect { my $self = shift; my $collectors = $self->{collectors}; my %samples_by_name; foreach my $collector ( @{ $collectors } ) { push @{ $samples_by_name{ $_->fullname } }, $_ for $collector->collect; } return map { my @results = @{ $samples_by_name{ $_ } }; my $first = $results[0]; @results > 1 ? MetricSamples( $first->fullname, $first->type, $first->help, [ map { @{ $_->samples } } @results ] ) : $first; } sort keys %samples_by_name; } =head2 render $str = $prometheus->render Returns a string in the Prometheus text exposition format containing the current values of all the registered metrics. =cut sub _render_label_value { my ( $v ) = @_; $v =~ s/(["\\])/\\$1/g; $v =~ s/\n/\\n/g; return qq("$v"); } sub _render_labels { my ( $labels ) = @_; return "" if !scalar @$labels; return "{" . join( ",", pairmap { $a . "=" . _render_label_value( $b ) } @$labels ) . "}"; } sub render { my $self = shift; return join "", map { my $metricsamples = $_; my $fullname = $metricsamples->fullname; my $help = $metricsamples->help; $help =~ s/\\/\\\\/g; $help =~ s/\n/\\n/g; "# HELP $fullname $help\n", "# TYPE $fullname " . $metricsamples->type . "\n", map { my $sample = $_; sprintf "%s%s %s\n", $sample->varname, _render_labels( $sample->labels ), $sample->value } @{ $metricsamples->samples } } $self->collect; } =head2 psgi_app $app = $prometheus->psgi_app Returns a new L application as a C reference. This application will render the metrics in the Prometheus text exposition format, suitable for scraping by the Prometheus collector. This application will respond to any C request, and reject requests for any other method. =cut sub psgi_app { my $self = shift; return sub { my $env = shift; my $method = $env->{REQUEST_METHOD}; $method eq "GET" or return [ 405, [ "Content-Type" => "text/plain" ], [ "Method $method not supported" ], ]; return [ 200, [ "Content-Type" => "text/plain; version=0.0.4; charset=utf-8" ], [ $self->render ], ]; }; } { package Net::Prometheus::_MetricGroup; sub new { my $class = shift; my ( $prometheus, %args ) = @_; return bless { prometheus => $prometheus, namespace => $args{namespace}, subsystem => $args{subsystem}, }, $class; } foreach my $method (qw( new_gauge new_counter new_summary new_histogram )) { no strict 'refs'; *$method = sub { my $self = shift; $self->{prometheus}->$method( namespace => $self->{namespace}, subsystem => $self->{subsystem}, @_, ); }; } } =head1 COLLECTORS The toplevel C object stores a list of "collector" instances, which are used to generate the values that will be made visible via the L method. A collector can be any object instance that has a method called C, which when invoked is passed no arguments and expected to return a list of L structures. @metricsamples = $collector->collect The L class is already a valid collector (and hence, so too are the individual metric type subclasses). This interface allows the creation of new custom collector objects, that more directly collect information to be exported. =cut =head1 TODO =over 8 =item * Split Registry out from toplevel instance. =item * Write some actual example programs. =back =cut =head1 AUTHOR Paul Evans =cut 0x55AA; Net-Prometheus-0.07/lib/Net/Prometheus000755001750001750 013362133440 16466 5ustar00leoleo000000000000Net-Prometheus-0.07/lib/Net/Prometheus/Counter.pm000444001750001750 424313362133440 20603 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2016 -- leonerd@leonerd.org.uk package Net::Prometheus::Counter; use strict; use warnings; use base qw( Net::Prometheus::Metric ); our $VERSION = '0.07'; use Carp; use constant _type => "counter"; __PACKAGE__->MAKE_child_class; =head1 NAME C - a monotonically-increasing counter metric =head1 SYNOPSIS use Net::Prometheus; my $client = Net::Prometheus->new; my $counter = $client->new_counter( name => "requests", help => "Number of received requests", ); sub handle_request { $counter->inc; ... } =head1 DESCRIPTION This class provides a counter metric - a value that monotonically increases, usually used to represent occurrences of some event that happens within the instrumented program. It is a subclass of L. =cut =head1 CONSTRUCTOR Instances of this class are not usually constructed directly, but instead via the L object that will serve it: $counter = $prometheus->new_counter( %args ) This takes the same constructor arguments as documented in L. =cut sub new { my $class = shift; my $self = $class->SUPER::new( @_ ); $self->{values} = {}; $self->inc( 0 ) if !$self->labelcount; return $self; } =head1 METHODS =cut =head2 inc $counter->inc( @label_values, $delta ) $counter->inc( \%labels, $delta ) $child->inc( $delta ) Increment the current value for the gauge. C<$delta> will default to 1 if not supplied and must be non-negative. =cut __PACKAGE__->MAKE_child_method( 'inc' ); sub _inc_child { my $self = shift; my ( $labelkey, $delta ) = @_; defined $delta or $delta = 1; $delta >= 0 or croak "Cannot increment a counter by a negative value"; $self->{values}{$labelkey} += $delta; } sub samples { my $self = shift; my $values = $self->{values}; return map { $self->make_sample( undef, $_, $values->{$_} ) } sort keys %$values; } =head1 AUTHOR Paul Evans =cut 0x55AA; Net-Prometheus-0.07/lib/Net/Prometheus/Gauge.pm000444001750001750 1053513362133440 20235 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2016,2018 -- leonerd@leonerd.org.uk package Net::Prometheus::Gauge; use strict; use warnings; use base qw( Net::Prometheus::Metric ); our $VERSION = '0.07'; use Carp; use constant _type => "gauge"; __PACKAGE__->MAKE_child_class; =head1 NAME C - a snapshot value-reporting metric =head1 SYNOPSIS use Net::Prometheus; my $client = Net::Prometheus->new; my $gauge = $client->new_gauge( name => "users", help => "Number of current users", ); my %users; ... $gauge->set( scalar keys %users ); =head1 DESCRIPTION This class provides a gauge metric - an arbitrary value that observes some snapshot of state at some instant in time. This is often used to report on the current usage of resources by the instrumented program, in a way that can decrease as well as increase. It is a subclass of L. =head2 Value-Reporting Functions As an alternative to using the C method to update the value of the gauge, a callback function can be used instead which should return the current value to report for that gauge. This function is invoked at collection time, meaning the reported value is up-to-date. These functions are invoked inline as part of the collection process, so they should be as small and lightweight as possible. Typical applications involve reporting the size of an array or hash within the implementation's code. $gauge->set_function( sub { scalar @items } ); $gauge->set_function( sub { scalar keys %things } ); =cut =head1 CONSTRUCTOR Instances of this class are not usually constructed directly, but instead via the L object that will serve it: $gauge = $prometheus->new_gauge( %args ) This takes the same constructor arguments as documented in L. =cut sub new { my $class = shift; my $self = $class->SUPER::new( @_ ); $self->{values} = {}; $self->{functions} = {}; $self->inc( 0 ) if !$self->labelcount; return $self; } =head1 METHODS =cut =head2 set $gauge->set( @label_values, $value ) $gauge->set( \%labels, $value ) $child->set( $value ) Sets the current value for the gauge. If the gauge has any labels defined, the values for them must be given first. =cut __PACKAGE__->MAKE_child_method( 'set' ); sub _set_child { my $self = shift; my ( $labelkey, $value ) = @_; $self->{values}{$labelkey} = $value; } =head2 set_function $gauge->set_function( @label_values, $func ) $gauge->set_function( \%labels, $func ) $child->set_function( $func ) Sets a value-returning callback function for the gauge. If the gauge is labeled, each label combination requires its own function. When invoked, the function will be passed no arguments and is expected to return a single value $value = $func->() =cut __PACKAGE__->MAKE_child_method( 'set_function' ); sub _set_function_child { my $self = shift; my ( $labelkey, $func ) = @_; # Need to store some sort of value so we still iterate on this labelkey # during ->samples $self->{values}{$labelkey} = undef; $self->{functions}{$labelkey} = $func; } =head2 inc $gauge->inc( @label_values, $delta ) $gauge->inc( \%labels, $delta ) $child->inc( $delta ) Increment the current value for the gauge. C<$delta> will default to 1 if not supplied. =cut __PACKAGE__->MAKE_child_method( 'inc' ); sub _inc_child { my $self = shift; my ( $labelkey, $delta ) = @_; defined $delta or $delta = 1; $self->{values}{$labelkey} += $delta; } =head2 dec $gauge->dec( @label_values, $delta ) $gauge->dec( \%labels, $delta ) $child->dec( $delta ) Decrement the current value for the gauge. C<$delta> will default to 1 if not supplied. =cut __PACKAGE__->MAKE_child_method( 'dec' ); sub _dec_child { my $self = shift; my ( $labelkey, $delta ) = @_; defined $delta or $delta = 1; $self->{values}{$labelkey} -= $delta; } sub samples { my $self = shift; my $values = $self->{values}; my $functions = $self->{functions}; return map { $self->make_sample( undef, $_, $functions->{$_} ? $functions->{$_}->() : $values->{$_} ) } sort keys %$values; } =head1 AUTHOR Paul Evans =cut 0x55AA; Net-Prometheus-0.07/lib/Net/Prometheus/Histogram.pm000444001750001750 724113362133440 21122 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2016-2018 -- leonerd@leonerd.org.uk package Net::Prometheus::Histogram; use strict; use warnings; use base qw( Net::Prometheus::Metric ); our $VERSION = '0.07'; use Carp; use List::Util 1.33 qw( any ); use constant _type => "histogram"; use constant DEFAULT_BUCKETS => [ 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10 ]; __PACKAGE__->MAKE_child_class; =head1 NAME C - count the distribution of numeric observations =head1 SYNOPSIS use Net::Prometheus; use Time::HiRes qw( time ); my $client = Net::Prometheus->new; my $histogram = $client->new_histogram( name => "request_seconds", help => "Summary request processing time", ); sub handle_request { my $start = time(); ... $summary->observe( time() - $start ); } =head1 DESCRIPTION This class provides a histogram metric - a count of the distribution of individual numerical observations into distinct buckets. These are usually reports of times. It is a subclass of L. =cut =head1 CONSTRUCTOR Instances of this class are not usually constructed directly, but instead via the L object that will serve it: $histogram = $prometheus->new_histogram( %args ) This takes the same constructor arguments as documented in L, and additionally the following: =over =item buckets => ARRAY A reference to an ARRAY containing numerical upper bounds for the buckets. =back =cut sub new { my $class = shift; my %opts = @_; my $buckets = $opts{buckets} || DEFAULT_BUCKETS; $buckets->[$_] > $buckets->[$_-1] or croak "Histogram bucket limits must be monotonically-increasing" for 1 .. $#$buckets; $opts{labels} and any { $_ eq "le" } @{ $opts{labels} } and croak "A Histogram may not have a label called 'le'"; my $self = $class->SUPER::new( @_ ); $self->{bounds} = [ @$buckets ]; # clone it $self->{bucketcounts} = {}; $self->{sums} = {}; if( !$self->labelcount ) { $self->{bucketcounts}{""} = [ ( 0 ) x ( @$buckets + 1 ) ]; $self->{sums}{""} = 0; } return $self; } =head2 observe $histogram->observe( @label_values, $value ) $histogram->observe( \%labels, $value ) $child->observe( $value ) Increment the histogram sum by the given value, and each bucket count by 1 where the value is less than or equal to the bucket upper bound. =cut __PACKAGE__->MAKE_child_method( 'observe' ); sub _observe_child { my $self = shift; my ( $labelkey, $value ) = @_; my $bounds = $self->{bounds}; my $buckets = $self->{bucketcounts}{$labelkey} ||= [ ( 0 ) x ( @$bounds + 1 ) ]; $value <= $bounds->[$_] and $buckets->[$_]++ for 0 .. $#$bounds; $buckets->[scalar @$bounds]++; $self->{sums}{$labelkey} += $value; } sub samples { my $self = shift; my $bounds = $self->{bounds}; my $bucketcounts = $self->{bucketcounts}; my $sums = $self->{sums}; return map { my $labelkey = $_; my $buckets = $bucketcounts->{$labelkey}; $self->make_sample( count => $labelkey, $buckets->[-1] ), $self->make_sample( sum => $labelkey, $sums->{$labelkey} ), ( map { $self->make_sample( bucket => $labelkey, $buckets->[$_], [ le => $bounds->[$_] ] ) } 0 .. $#$bounds ), $self->make_sample( bucket => $labelkey, $buckets->[-1], [ le => "+Inf" ] ); } sort keys %$sums; } =head1 AUTHOR Paul Evans =cut 0x55AA; Net-Prometheus-0.07/lib/Net/Prometheus/Metric.pm000444001750001750 1706213362133440 20432 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2016 -- leonerd@leonerd.org.uk package Net::Prometheus::Metric; use strict; use warnings; our $VERSION = '0.07'; use Carp; our @CARP_NOT = qw( Net::Prometheus ); use Ref::Util qw( is_hashref ); use Net::Prometheus::Types qw( Sample MetricSamples ); use constant CHILDCLASS => "Net::Prometheus::Metric::_Child"; =head1 NAME C - the base class for observed metrics =head1 DESCRIPTION This class provides the basic methods shared by the concrete subclasses, =over 2 =item * L - a snapshot value-reporting metric =item * L - a monotonically-increasing counter metric =item * L - summarise individual numeric observations =item * L - count the distribution of numeric observations =back =cut =head1 CONSTRUCTOR =cut =head2 new $metric = Net::Prometheus::Metric->new( name => $name, help => $help, ) The constructor is not normally used directly by instrumented code. Instead it is more common to use one of the C methods on the containing L client instance so that the new metric is automatically registered as a collector, and gets exported by the render method. $metric = $prometheus->new_counter( name => $name, help => $help, ) In either case, it returns a newly-constructed metric. Takes the following named arguments: =over =item namespace => STR =item subsystem => STR Optional strings giving the namespace and subsystem name parts of the variable name. =item name => STR The basename of the exported variable. =item help => STR Descriptive help text for the variable. =item labels => ARRAY of STR Optional ARRAY reference giving the names of labels for the metric. =back =cut sub new { my $class = shift; my %args = @_; defined $args{name} or croak "Required 'name' argument missing"; defined $args{help} or croak "Required 'help' argument missing"; my $fullname = join "_", grep { defined } $args{namespace}, $args{subsystem}, $args{name}; my $labellist = $args{labels} || []; # See # https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels $fullname =~ m/^[a-zA-Z_:][a-zA-Z0-9_:]*$/ or croak "Invalid metric name '$fullname'"; $_ =~ m/^[a-zA-Z_][a-zA-Z0-9_]*$/ or croak "Invalid label name '$_'" for @$labellist; $_ =~ m/^__/ and croak "Label name '$_' is reserved" for @$labellist; return bless { fullname => $fullname, help => $args{help}, labels => $labellist, labelvalues => {}, }, $class; } =head1 METHODS =cut =head2 fullname $fullname = $metric->fullname Returns the full name for the metric. This is formed by joining any of the defined values for C, C and C with C<'_'>. =cut sub fullname { my $self = shift; return $self->{fullname}; } =head2 labelcount $labels = $metric->labelcount Returns the number of labels defined for this metric. =cut sub labelcount { my $self = shift; return scalar @{ $self->{labels} }; } =head2 labels $child = $metric->labels( @values ) $child = $metric->labels( { name => $value, name => $value, ... } ) Returns a child metric to represent the general one with the given set of labels. The label values may be provided either in a list corresponding to the list of label names given at construction time, or by name in a single HASH reference. The child instance supports the same methods to control the value of the reported metric as the parent metric object, except that any label values are already provided. This object may be cached for efficiency. =cut sub labels { my $self = shift; my @values = @_; if( @values == 1 and is_hashref( $values[0] ) ) { my $labels = $self->{labels}; my $href = $values[0]; defined $href->{$_} or croak "No value for $_ label given" for @$labels; @values = @{$href}{ @$labels }; } my $labelcount = $self->labelcount; @values >= $labelcount or croak "Insufficient values given for labels"; @values == $labelcount or croak "Too many values given for labels"; length $values[$_] or croak "Value for $self->{labels}[$_] may not empty" for 0 .. $#values; my $labelkey = join "\x00", map { # Encode \x00 or \x01 as \x{01}0 or \x{01}1 in order to escape the \x00 # but preserve full leixcal ordering my $value = $_; $value =~ s/\x01/\x011/g; $value =~ s/\x00/\x010/g; $value; } @values; $self->{labelvalues}{$labelkey} = \@values; return $self->CHILDCLASS->new( $self, $labelkey ); } { package Net::Prometheus::Metric::_Child; use constant { METRIC => 0, LABELKEY => 1, }; sub new { my $class = shift; my ( $metric, $labelkey ) = @_; return bless [ $metric, $labelkey ], $class; } sub metric { shift->[METRIC] } sub labelkey { shift->[LABELKEY] } } # A metaclass method for declaring the child class sub MAKE_child_class { my $class = shift; my $childclass = "${class}::_Child"; no strict 'refs'; # The careful ordering of these two lines should make it possible to # further subclass metrics and metric child classes recursively @{"${childclass}::ISA"} = $class->CHILDCLASS; *{"${class}::CHILDCLASS"} = sub() { $childclass }; } # A metaclass method for declaring what Metric subclass methods are proxied # via child instances sub MAKE_child_method { my $class = shift; my ( $method ) = @_; no strict 'refs'; *{"${class}::${method}"} = sub { my $self = shift; my @values = splice @_, 0, is_hashref( $_[0] ) ? 1 : $self->labelcount; $self->labels( @values )->$method( @_ ); }; my $childmethod = "_${method}_child"; *{"${class}::_Child::${method}"} = sub { my $self = shift; $self->metric->$childmethod( $self->labelkey, @_ ); }; } =head2 make_sample $sample = $metric->make_sample( $suffix, $labelkey, $value, $extralabels ) Returns a new L structure to represent the given value, by expanding the opaque C<$labelkey> value into its actual label names and values and appending the given suffix (which may be an empty string) to the metric's fullname. If provided, the suffix will be separated by an underscore C<'_'>. If provided, C<$extralabels> provides more label names and values to be added to the sample. =cut sub make_sample { my $self = shift; my ( $suffix, $labelkey, $value, $extralabels ) = @_; my $labelnames = $self->{labels}; my $labelvalues = $self->{labelvalues}{$labelkey}; return Sample( ( $suffix ? $self->fullname . "_$suffix" : $self->fullname ), [ ( map { $labelnames->[$_], $labelvalues->[$_] } 0 .. $#$labelnames ), @{ $extralabels || [] } ], $value, ); } sub collect { my $self = shift; return MetricSamples( $self->fullname, $self->_type, $self->{help}, [ $self->samples ], ); } =head2 samples @samples = $metric->samples An abstract method in this class, this method is intended to be overridden by subclasses. Called during the value collection process, this method should return a list of L instances containing the values to report from this metric. =cut sub samples { croak "Abstract Net::Prometheus::Metric->samples invoked directly"; } =head1 AUTHOR Paul Evans =cut 0x55AA; Net-Prometheus-0.07/lib/Net/Prometheus/ProcessCollector.pm000444001750001750 550413362133440 22452 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2016 -- leonerd@leonerd.org.uk package Net::Prometheus::ProcessCollector; use strict; use warnings; our $VERSION = '0.07'; use Net::Prometheus::Types qw( MetricSamples Sample ); =head1 NAME C - obtain a process collector for the OS =head1 SYNOPSIS use Net::Prometheus::ProcessCollector; my $collector = Net::Prometheus::ProcessCollector->new; =head1 DESCRIPTION This module-loading package provides a method that attempts to load a process collector appropriate for the host OS it is running on. The following OS-specific modules are provided with this distribution: =over 2 =item * L =back Other OSes may be supported by 3rd-party CPAN modules by following this naming pattern based on the value of the C<$^O> variable on the OS concerned. =cut =head1 MAGIC CONSTRUCTORS =cut =head2 new $collector = Net::Prometheus::ProcessCollector->new( %args ) Attempts to construct a new process collector for the OS named by C<$^O>, passing in any extra arguments into the C constructor for the specific class. If no perl module is found under the appropriate file name, C is returned. If any other error occurs while loading or constructing the instance, the exception is thrown as normal. Typically a process exporter should support the following named arguments: =over =item prefix => STR A prefix to prepend on all the exported variable names. If not provided, the default should be C<"process">. =item labels => ARRAY Additional labels to set on exported variables. If not provided, no extra labels will be set. =back =cut sub new { my $class = shift; $class->for_OS( $^O, @_ ); } =head2 for_OS $collector = Net::Prometheus::ProcessCollector->for_OS( $os, @args ) Attempts to construct a new process collector for the named OS. Except under especially-exceptional circumstances, you don't want to call this method. Call L instead. =cut sub for_OS { shift; # class my ( $os, @args ) = @_; my $pkg = __PACKAGE__ . "::$os"; ( my $file = "$pkg.pm" ) =~ s{::}{/}g; if( !eval { require $file } ) { return if $@ =~ m/^Can't locate \Q$file\E in \@INC/; die $@; } return $pkg->new( @args ); } # Methods for subclasses sub __new { my $class = shift; my %args = @_; return bless { prefix => $args{prefix} || "process", labels => $args{labels} || [], }, $class; } sub _make_metric { my $self = shift; my ( $varname, $value, $type, $help ) = @_; my $prefix = $self->{prefix}; return MetricSamples( "${prefix}_$varname", $type, $help, [ Sample( "${prefix}_$varname", $self->{labels}, $value ) ] ); } 0x55AA; Net-Prometheus-0.07/lib/Net/Prometheus/Summary.pm000444001750001750 473013362133440 20622 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2016 -- leonerd@leonerd.org.uk package Net::Prometheus::Summary; use strict; use warnings; use base qw( Net::Prometheus::Metric ); our $VERSION = '0.07'; use Carp; use List::Util 1.33 qw( any ); use constant _type => "summary"; __PACKAGE__->MAKE_child_class; =head1 NAME C - summarise individual numeric observations =head1 SYNOPSIS use Net::Prometheus; use Time::HiRes qw( time ); my $client = Net::Prometheus->new; my $summary = $client->new_summary( name => "request_seconds", help => "Summary request processing time", ); sub handle_request { my $start = time(); ... $summary->observe( time() - $start ); } =head1 DESCRIPTION This class provides a summary metric - a combination of a running total and a counter, that can be used to report on total and average values of observations, usually times. It is a subclass of L. =cut =head1 CONSTRUCTOR Instances of this class are not usually constructed directly, but instead via the L object that will serve it: $summary = $prometheus->new_summary( %args ) This takes the same constructor arguments as documented in L. =cut sub new { my $class = shift; my %opts = @_; $opts{labels} and any { $_ eq "quantile" } @{ $opts{labels} } and croak "A Summary may not have a label called 'quantile'"; my $self = $class->SUPER::new( @_ ); $self->{counts} = {}; $self->{sums} = {}; if( !$self->labelcount ) { $self->{counts}{""} = $self->{sums}{""} = 0; } return $self; } =head2 observe $summary->observe( @label_values, $value ) $summary->observe( \%labels, $value ) $child->observe( $value ) Increment the summary sum by the given value, and the count by 1. =cut __PACKAGE__->MAKE_child_method( 'observe' ); sub _observe_child { my $self = shift; my ( $labelkey, $value ) = @_; $self->{counts}{$labelkey} += 1; $self->{sums} {$labelkey} += $value; } sub samples { my $self = shift; my $counts = $self->{counts}; my $sums = $self->{sums}; return map { $self->make_sample( count => $_, $counts->{$_} ), $self->make_sample( sum => $_, $sums->{$_} ) } sort keys %$counts; } =head1 AUTHOR Paul Evans =cut 0x55AA; Net-Prometheus-0.07/lib/Net/Prometheus/Types.pm000444001750001750 417413362133440 20273 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2016 -- leonerd@leonerd.org.uk package Net::Prometheus::Types; use strict; use warnings; our $VERSION = '0.07'; use Exporter 'import'; our @EXPORT_OK; use Struct::Dumb qw( readonly_struct ); =head1 NAME C - a collection of support structure types =head1 SYNOPSIS use Net::Prometheus::Types qw( Sample ); my $ob = Sample( variable => [], 123 ); print "The sample relates to a variable called ", $ob->varname; =head1 DESCRIPTION This package contains some simple support structures that assist with other parts of the L distribution. Each type is exported as a constructor function. =cut =head1 TYPES =cut =head2 Sample This structure represents an individual value sample; associating a numerical value with a named variable and set of label values. $sample = Sample( $varname, $labels, $value ) =head3 varname $varname = $sample->varname The string variable name. This is the basic name, undecorated by label values. =head3 labels $labels = $sample->labels A reference to an even-sized ARRAY containing name/value pairs for the labels. Label values should be raw unescaped strings. =head3 value $sample->value The numerical value observed. =cut push @EXPORT_OK, qw( Sample ); readonly_struct Sample => [qw( varname labels value )]; =head2 MetricSamples This structure represents all the samples made about a given metric, including metadata about the metric itself. $samples = MetricSamples( $fullname, $type, $help, $samples ) =head3 fullname A string giving the fullname of the metric. =head3 type A string, one of C<'gauge'>, C<'counter'>, C<'summary'> or C<'histogram'>. =head3 help A string containing the descriptive help message text. =head3 samples A reference to an ARRAY containing individual L instances. =cut push @EXPORT_OK, qw( MetricSamples ); readonly_struct MetricSamples => [qw( fullname type help samples )]; =head1 AUTHOR Paul Evans =cut 0x55AA; Net-Prometheus-0.07/lib/Net/Prometheus/ProcessCollector000755001750001750 013362133440 21753 5ustar00leoleo000000000000Net-Prometheus-0.07/lib/Net/Prometheus/ProcessCollector/linux.pm000444001750001750 1166313362133440 23634 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2016 -- leonerd@leonerd.org.uk package Net::Prometheus::ProcessCollector::linux; use strict; use warnings; use base qw( Net::Prometheus::ProcessCollector ); our $VERSION = '0.07'; use constant { TICKS_PER_SEC => 100, BYTES_PER_PAGE => 4096, }; =head1 NAME C - Process Collector for F OS =head1 SYNOPSIS use Net::Prometheus; use Net::Prometheus::ProcessCollector::linux; my $prometheus = Net::Prometheus->new; $prometheus->register( Net::Prometheus::ProcessCollector::linux->new ); =head1 DESCRIPTION This class provides a L collector instance to provide process-wide metrics for a process running on the F operating system. At collection time, if the requested process does not exist, no metrics are returned. =head2 Other Process Collection The C argument allows the collector to collect from processes other than the one actually running the code. Note also that scraping processes owned by other users may not be possible for non-root users. In particular, most systems do not let non-root users see the L directory of processes they don't own. In this case, the C metric will not be returned. =cut =head1 CONSTRUCTOR =head2 new $collector = Net::Prometheus::ProcessCollector::linux->new( %args ) As well as the default arguments supported by L, the following extra named arguments are recognised: =over =item pid => STR The numerical PID to collect information about; defaults to the string C<"self"> allowing the exporter to collect information about itself, even over fork calls. If the collector is collecting from C<"self"> or from a numerical PID that matches its own PID, then it will subtract 1 from the count of open file handles, to account for the C handle being used to collect that count. If it is collecting a different process, it will not. =back =cut my $BOOTTIME; sub new { my $class = shift; my %args = @_; # To report process_start_time_seconds correctly, we need the machine boot # time if( !defined $BOOTTIME ) { foreach my $line ( do { open my $fh, "<", "/proc/stat"; <$fh> } ) { next unless $line =~ m/^btime /; $BOOTTIME = +( split m/\s+/, $line )[1]; last; } } my $self = $class->__new( %args ); $self->{pid} = $args{pid} || "self"; return $self; } sub _read_procfile { my $self = shift; my ( $path ) = @_; open my $fh, "<", "/proc/$self->{pid}/$path" or return; return <$fh>; } sub _open_fds { my $self = shift; my $pid = $self->{pid}; opendir my $dirh, "/proc/$pid/fd" or return undef; my $count = ( () = readdir $dirh ); $count -= 1 if $pid eq "self" or $pid == $$; # subtract 1 for $dirh itself return $count; } sub _limit_fds { my $self = shift; my $line = ( grep m/^Max open files/, $self->_read_procfile( "limits" ) )[0]; defined $line or return undef; # Max open files $SOFT $HARD return +( split m/\s+/, $line )[3]; } sub collect { my $self = shift; my $statline = $self->_read_procfile( "stat" ); defined $statline or return; # process missing # /proc/PID/stat contains PID (COMM) more fields here my @statfields = split( m/\s+/, ( $statline =~ m/\)\s+(.*)/ )[0] ); my $utime = $statfields[11] / TICKS_PER_SEC; my $stime = $statfields[12] / TICKS_PER_SEC; my $starttime = $statfields[19] / TICKS_PER_SEC; my $vsize = $statfields[20]; my $rss = $statfields[21] * BYTES_PER_PAGE; my $open_fds = $self->_open_fds; my $limit_fds = $self->_limit_fds; return $self->_make_metric( cpu_user_seconds_total => $utime, "counter", "Total user CPU time spent in seconds" ), $self->_make_metric( cpu_system_seconds_total => $stime, "counter", "Total system CPU time spent in seconds" ), $self->_make_metric( cpu_seconds_total => $utime + $stime, "counter", "Total user and system CPU time spent in seconds" ), $self->_make_metric( virtual_memory_bytes => $vsize, "gauge", "Virtual memory size in bytes" ), $self->_make_metric( resident_memory_bytes => $rss, "gauge", "Resident memory size in bytes" ), ( defined $open_fds ? $self->_make_metric( open_fds => $open_fds, "gauge", "Number of open file handles" ) : () ), ( defined $limit_fds ? $self->_make_metric( max_fds => $limit_fds, "gauge", "Maximum number of allowed file handles" ) : () ), $self->_make_metric( start_time_seconds => $BOOTTIME + $starttime, "gauge", "Unix epoch time the process started at" ), # TODO: consider some stats out of /proc/PID/io } =head1 AUTHOR Paul Evans =cut 0x55AA; Net-Prometheus-0.07/t000755001750001750 013362133440 13302 5ustar00leoleo000000000000Net-Prometheus-0.07/t/00use.t000444001750001750 73513362133440 14545 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use_ok( 'Net::Prometheus' ); use_ok( 'Net::Prometheus::Types' ); use_ok( 'Net::Prometheus::Gauge' ); use_ok( 'Net::Prometheus::Counter' ); use_ok( 'Net::Prometheus::Summary' ); use_ok( 'Net::Prometheus::Histogram' ); use_ok( 'Net::Prometheus::ProcessCollector' ); # Each process collector should at least *compile* when not on its own host OS use_ok( 'Net::Prometheus::ProcessCollector::linux' ); done_testing; Net-Prometheus-0.07/t/01metric.t000444001750001750 360613362133440 15255 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Test::Fatal; use Net::Prometheus::Metric; { is( Net::Prometheus::Metric->new( name => "basename", help => "", )->fullname, "basename", 'fullname for name only' ); is( Net::Prometheus::Metric->new( subsystem => "subsys", name => "basename", help => "", )->fullname, "subsys_basename", 'fullname for subsystem+name' ); is( Net::Prometheus::Metric->new( namespace => "namesp", name => "basename", help => "", )->fullname, "namesp_basename", 'fullname for namespace+name' ); is( Net::Prometheus::Metric->new( namespace => "namesp", subsystem => "subsys", name => "basename", help => "", )->fullname, "namesp_subsys_basename", 'fullname for namespace+subsystem+name' ); } # samples { my $metric = Net::Prometheus::Metric->new( name => "basename", help => "", ); my $sample = $metric->make_sample( undef, "", 123 ); is( $sample->varname, "basename", '$sample->varname' ); is_deeply( $sample->labels, [], '$sample->labels' ); is( $sample->value, 123, '$sample->value' ); is( $metric->make_sample( "suffix", "", 456 )->varname, "basename_suffix", '$sample->varname with suffix', ); } # exceptions { ok( exception { Net::Prometheus::Metric->new( name => "with_no_help", ) }, 'Metric without help dies' ); ok( exception { Net::Prometheus::Metric->new( help => "This metric lacks a name", ) }, 'Metric without name dies' ); ok( exception { Net::Prometheus::Metric->new( name => "hello/world", help => "", ) }, 'Invalid metric name dies' ); } done_testing; Net-Prometheus-0.07/t/02labels.t000444001750001750 302713362133440 15232 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Test::Fatal; use Net::Prometheus::Metric; # samples { my $metric = Net::Prometheus::Metric->new( name => "basename", help => "", labels => [qw( labelname )], ); # TODO: child instances are still undocumented my $sample = $metric->make_sample( undef, $metric->labels( "value" )->labelkey, 123 ); is( $sample->varname, "basename", '$sample->varname' ); is_deeply( $sample->labels, [ labelname => "value" ], '$sample->labels' ); is( $sample->value, 123, '$sample->value' ); is_deeply( $metric->make_sample( undef, $metric->labels( "value" )->labelkey, 123, [ another => "label" ], )->labels, [ labelname => "value", another => "label" ], '$sample->labels with morelabels' ); } # exceptions { ok( exception { Net::Prometheus::Metric->new( name => "metric", labels => [ "ab/cd" ], help => "", ) }, 'Invalid label name dies' ); ok( exception { Net::Prometheus::Metric->new( name => "metric", labels => [ "__name" ], help => "", ) }, 'Reserved label name dies' ); ok( exception { my $metric = Net::Prometheus::Metric->new( name => "metric", labels => [ "label" ], help => "", ); $metric->labels( "" ); }, 'Empty label value dies' ); } done_testing; Net-Prometheus-0.07/t/10gauge.t000444001750001750 732713362133440 15066 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Net::Prometheus::Gauge; sub HASHfromSample { my ( $sample ) = @_; return { map { $_, $sample->$_ } qw( varname labels value ) }; } # No labels { my $gauge = Net::Prometheus::Gauge->new( name => "test_gauge", help => "A testing gauge", ); ok( defined $gauge, 'defined $gauge' ); my @samples = $gauge->samples; is( scalar @samples, 1, '$gauge->samples yields 1 sample' ); is_deeply( HASHfromSample( $samples[0] ), { varname => "test_gauge", labels => [], value => 0, }, '$samples[0] initially' ); $gauge->inc; @samples = $gauge->samples; is( $samples[0]->value, 1, 'sample->value after $gauge->inc' ); $gauge->inc( 10 ); @samples = $gauge->samples; is( $samples[0]->value, 11, 'sample->value after $gauge->inc( 10 )' ); $gauge->dec( 5 ); @samples = $gauge->samples; is( $samples[0]->value, 6, 'sample->value after $gauge->dec( 5 )' ); } # Functions { my $gauge = Net::Prometheus::Gauge->new( name => "func_gauge", help => "A gauge reporting a function", ); my $value; $gauge->set_function( sub { $value } ); $value = 10; is( ( $gauge->samples )[0]->value, 10, 'sample->value from function' ); $value = 20; is( ( $gauge->samples )[0]->value, 20, 'sample->value updates' ); } # One label { my $gauge = Net::Prometheus::Gauge->new( name => "labeled_gauge", help => "A gauge with a label", labels => [qw( lab )], ); is_deeply( [ $gauge->samples ], [], '$gauge->samples initially empty' ); $gauge->set( one => 1 ); $gauge->set( { lab => "two" }, 2 ); # FRAGILE: depends on the current implementation sorting these my @samples = $gauge->samples; is( scalar @samples, 2, '$gauge->samples yields 2 samples' ); is_deeply( [ map { HASHfromSample( $_ ) } @samples ], [ { varname => "labeled_gauge", labels => [ lab => "one" ], value => 1 }, { varname => "labeled_gauge", labels => [ lab => "two" ], value => 2 }, ], '@samples' ); $gauge->labels( "three" )->set( 3 ); is_deeply( [ map { HASHfromSample( $_ ) } $gauge->samples ], [ { varname => "labeled_gauge", labels => [ lab => "one" ], value => 1 }, { varname => "labeled_gauge", labels => [ lab => "three" ], value => 3 }, { varname => "labeled_gauge", labels => [ lab => "two" ], value => 2 }, ], '@samples after adding "three"' ); } # Functions + label { my $gauge = Net::Prometheus::Gauge->new( name => "labeled_func_gauge", help => "A gauge reporting a function with a label", labels => [qw( lab )], ); my $value; $gauge->set_function( one => sub { $value } ); $value = 50; is( ( $gauge->samples )[0]->value, 50, 'sample->value from function with label' ); } # Two labels { my $gauge = Net::Prometheus::Gauge->new( name => "multidimensional_gauge", help => "A gauge with two labels", labels => [qw( x y )], ); $gauge->set( 0 => 0 => 10 ); $gauge->set( 0 => 1 => 20 ); $gauge->set( { x => 1, y => 0 }, 30 ); $gauge->set( { x => 1, y => 1 }, 40 ); is_deeply( [ map { HASHfromSample( $_ ) } $gauge->samples ], [ { varname => "multidimensional_gauge", labels => [ x => "0", y => "0" ], value => 10 }, { varname => "multidimensional_gauge", labels => [ x => "0", y => "1" ], value => 20 }, { varname => "multidimensional_gauge", labels => [ x => "1", y => "0" ], value => 30 }, { varname => "multidimensional_gauge", labels => [ x => "1", y => "1" ], value => 40 }, ], '@samples after adding "three"' ); } done_testing; Net-Prometheus-0.07/t/11counter.t000444001750001750 144113362133440 15445 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Net::Prometheus::Counter; sub HASHfromSample { my ( $sample ) = @_; return { map { $_, $sample->$_ } qw( varname labels value ) }; } { my $counter = Net::Prometheus::Counter->new( name => "test_total", help => "A testing counter", ); ok( defined $counter, 'defined $counter' ); my @samples = $counter->samples; is( scalar @samples, 1, '$counter->samples yields 1 sample' ); is_deeply( HASHfromSample( $samples[0] ), { varname => "test_total", labels => [], value => 0 }, '$samples[0] initially' ); $counter->inc; is_deeply( HASHfromSample( ( $counter->samples )[0] ), { varname => "test_total", labels => [], value => 1 }, '$samples[0]' ); } done_testing; Net-Prometheus-0.07/t/12summary.t000444001750001750 234313362133440 15466 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Test::Fatal; use Net::Prometheus::Summary; sub HASHfromSample { my ( $sample ) = @_; return { map { $_, $sample->$_ } qw( varname labels value ) }; } { my $summary = Net::Prometheus::Summary->new( name => "test", help => "A testing summary", ); ok( defined $summary, 'defined $summary' ); is_deeply( [ map { HASHfromSample( $_ ) } $summary->samples ], [ # Slightly fragile as we depend on 'count' coming before 'sum' { varname => "test_count", labels => [], value => 0 }, { varname => "test_sum", labels => [], value => 0 }, ], '$summary->samples initially' ); $summary->observe( 5 ); is_deeply( [ map { HASHfromSample( $_ ) } $summary->samples ], [ { varname => "test_count", labels => [], value => 1 }, { varname => "test_sum", labels => [], value => 5 }, ], '$summary->samples after ->observe( 5 )' ); } # exceptions { ok( exception { Net::Prometheus::Summary->new( name => "test", labels => [ "quantile" ], help => "", ); }, 'Summary with "quantile" label dies' ); } done_testing; Net-Prometheus-0.07/t/13histogram.t000444001750001750 524113362133440 15767 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Test::Fatal; use Net::Prometheus::Histogram; sub HASHfromSample { my ( $sample ) = @_; return { map { $_, $sample->$_ } qw( varname labels value ) }; } { my $histogram = Net::Prometheus::Histogram->new( name => "test", help => "A testing histogram", buckets => [ 1, 2, 5 ], ); ok( defined $histogram, 'defined $histogram' ); is_deeply( [ map { HASHfromSample( $_ ) } $histogram->samples ], [ # Slightly fragile as we depend on 'count' coming before 'sum' { varname => "test_count", labels => [], value => 0 }, { varname => "test_sum", labels => [], value => 0 }, { varname => "test_bucket", labels => [ le => 1 ], value => 0 }, { varname => "test_bucket", labels => [ le => 2 ], value => 0 }, { varname => "test_bucket", labels => [ le => 5 ], value => 0 }, { varname => "test_bucket", labels => [ le => "+Inf" ], value => 0 }, ], '$histogram->samples initially' ); $histogram->observe( 5 ); is_deeply( [ map { HASHfromSample( $_ ) } $histogram->samples ], [ { varname => "test_count", labels => [], value => 1 }, { varname => "test_sum", labels => [], value => 5 }, { varname => "test_bucket", labels => [ le => 1 ], value => 0 }, { varname => "test_bucket", labels => [ le => 2 ], value => 0 }, { varname => "test_bucket", labels => [ le => 5 ], value => 1 }, { varname => "test_bucket", labels => [ le => "+Inf" ], value => 1 }, ], '$histogram->samples after ->observe( 5 )' ); $histogram->observe( 1.5 ); is_deeply( [ map { HASHfromSample( $_ ) } $histogram->samples ], [ { varname => "test_count", labels => [], value => 2 }, { varname => "test_sum", labels => [], value => 6.5 }, { varname => "test_bucket", labels => [ le => 1 ], value => 0 }, { varname => "test_bucket", labels => [ le => 2 ], value => 1 }, { varname => "test_bucket", labels => [ le => 5 ], value => 2 }, { varname => "test_bucket", labels => [ le => "+Inf" ], value => 2 }, ], '$histogram->samples after ->observe( 1.5 )' ); } # exceptions { ok( exception { Net::Prometheus::Histogram->new( name => "test", labels => [ "le" ], help => "", ); }, 'Histogram with "le" label dies' ); ok( exception { Net::Prometheus::Histogram->new( name => "test", help => "", buckets => [ 5, 5 ], ); }, 'Histogram with non-monotonic buckets dies' ); } done_testing; Net-Prometheus-0.07/t/20client.t000444001750001750 316613362133440 15252 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Net::Prometheus; my $client = Net::Prometheus->new( disable_process_collector => 1, disable_perl_collector => 1, ); ok( defined $client, 'defined $client' ); # initially empty is( $client->render, "", '$client->render gives empty string' ); # with some metrics { $client->new_gauge( name => "gauge", help => "A gauge metric", )->set( 123 ); $client->new_counter( name => "counter", help => "A counter metric", )->inc(); is( $client->render, <<'EOF', '$client->render gives metric results' ); # HELP counter A counter metric # TYPE counter counter counter 1 # HELP gauge A gauge metric # TYPE gauge gauge gauge 123 EOF } # HELP escaping { my $client = Net::Prometheus->new( disable_process_collector => 1, disable_perl_collector => 1, ); $client->new_gauge( name => "gauge", help => "with\nlinefeed", )->set( 0 ); is( $client->render, <<'EOF', '$client->render escapes HELP text' ); # HELP gauge with\nlinefeed # TYPE gauge gauge gauge 0 EOF } # metric groups { is( $client->new_metricgroup( namespace => "namespc" )->new_gauge( subsystem => "subsys", name => "gauge", help => "" )->fullname, "namespc_subsys_gauge", 'Metric Group can provide default namespace' ); is( $client->new_metricgroup( subsystem => "subsys", )->new_gauge( name => "gauge", help => "" )->fullname, "subsys_gauge", 'Metric Group can provide default subsystem' ); } done_testing; Net-Prometheus-0.07/t/21label-rendering.t000444001750001750 340313362133440 17021 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Net::Prometheus; use Net::Prometheus::Metric; my $sample; no warnings 'redefine'; local *Net::Prometheus::Metric::_type = sub { "untyped" }; local *Net::Prometheus::Metric::samples = sub { return $sample; }; my $client = Net::Prometheus->new( disable_process_collector => 1, disable_perl_collector => 1, ); { my $metric = $client->register( Net::Prometheus::Metric->new( name => "metric", labels => [ "lab" ], help => "", ) ); sub test_label { my ( $label, $str, $name ) = @_; $sample = $metric->make_sample( "", $metric->labels( $label )->labelkey, 0 ); is( ( split m/\n/, $client->render )[2], qq(metric{lab="$str"} 0), "render for $name" ); } test_label( "a", "a", 'basic label', ); test_label( "val here", "val here", 'label with whitespace', ); test_label( q("quoted"), q(\"quoted\"), 'label with quotes', ); test_label( 'ab\cd', "ab\\\\cd", 'label with backslash', ); test_label( "line\nfeed", "line\\nfeed", 'label with linefeed', ); test_label( "with\0null", "with\0null", 'label with NUL byte', ); $client->unregister( $metric ); is( $client->render, "", 'render after ->unregister' ); } { my $metric = $client->register( Net::Prometheus::Metric->new( name => "metric", labels => [ "x", "y" ], help => "", ) ); $sample = $metric->make_sample( "", $metric->labels( "a", "b" )->labelkey, 0 ); is( ( split m/\n/, $client->render )[2], q(metric{x="a",y="b"} 0), '_render_value for multi-dimensional label' ); $client->unregister( $metric ); } done_testing; Net-Prometheus-0.07/t/22metric-grouping.t000444001750001750 161213362133440 17103 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Net::Prometheus; use Net::Prometheus::Types qw( MetricSamples Sample ); my $client = Net::Prometheus->new( disable_process_collector => 1, disable_perl_collector => 1, ); { package CustomCollector; sub new { my $class = shift; bless [ @_ ], $class; } sub collect { shift->[0]->() } } $client->register( CustomCollector->new( sub { MetricSamples( "metric", gauge => "", [ Sample( "metric", [ label => "a" ], 123 ) ] ) } ) ); $client->register( CustomCollector->new( sub { MetricSamples( "metric", gauge => "", [ Sample( "metric", [ label => "b" ], 123 ) ] ) } ) ); my @samples = $client->collect; is( scalar @samples, 1, '$client->collect returns 1 MetricSamples group' ); is( scalar @{ $samples[0]->samples }, 2, 'MetricSamples group contains both samples' ); done_testing; Net-Prometheus-0.07/t/30psgi.t000444001750001750 115113362133440 14727 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use List::Util 1.29 qw( pairgrep ); use Net::Prometheus; my $client = Net::Prometheus->new; my $app = $client->psgi_app; ok( defined $app, 'defined $client->psgi_app' ); is( ref $app, "CODE", '$app is CODE' ); ok( my $resp = $app->({ REQUEST_METHOD => "GET" }), '$app->() returns a response' ); is( $resp->[0], 200, '$resp->[0] is 200' ); is( ( pairgrep { $a eq "Content-Type" } @{ $resp->[1] } )[1], "text/plain; version=0.0.4; charset=utf-8", '$resp->[1] contains response headers' ); # TODO: test join "", @{ $resp->[2] } done_testing; Net-Prometheus-0.07/t/40process-collector.t000444001750001750 37513362133440 17417 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Net::Prometheus::ProcessCollector; # unknown OS { ok( !defined Net::Prometheus::ProcessCollector->for_OS( "unknown" ), '->for_OS on unknown OS does not fail' ); } done_testing; Net-Prometheus-0.07/t/41process-collector-linux.t000444001750001750 242313362133440 20571 0ustar00leoleo000000000000 use strict; use warnings; use Test::More; plan skip_all => "Not for this OS" unless $^O eq "linux"; use Net::Prometheus::ProcessCollector::linux; sub _find_metric { my ( $name, @samples ) = @_; ( grep { $_->fullname eq $name } @samples )[0]; } { my $collector = Net::Prometheus::ProcessCollector::linux->new; ok( defined $collector, '$collector is defined' ); my @samples = $collector->collect; ok( scalar @samples, '$collector->collect gave some samples' ); my $metric = _find_metric( "process_cpu_seconds_total", @samples ); ok( $metric, 'found process_cpu_seconds_total' ); my $sample = $metric->samples->[0]; is( $sample->varname, "process_cpu_seconds_total", 'sample varname' ); is_deeply( $sample->labels, [], 'sample labels' ); ok( $sample->value > 0, 'sample value above zero' ); } # overridden names { my $collector = Net::Prometheus::ProcessCollector::linux->new( prefix => "prefix_process", labels => [ label => "value" ], ); my @samples = $collector->collect; my $metric = _find_metric( "prefix_process_cpu_seconds_total", @samples ); ok( $metric, 'found process_cpu_seconds_total' ); my $sample = $metric->samples->[0]; is_deeply( $sample->labels, [ label => "value" ], 'sample labels' ); } done_testing; Net-Prometheus-0.07/t/99pod.t000444001750001750 25713362133440 14554 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();