Repository: smilebasti/npmGrafStats Branch: main Commit: 445235f4b844 Files: 18 Total size: 175.3 KB Directory structure: gitextract_tdicfddf/ ├── .dockerignore ├── Dockerfile ├── LICENSE ├── README.md ├── changelog.md ├── docker-compose.yml ├── npmGrafStats Map Dashboard v3.1+ InfluxDBv2 NO filter.json ├── npmGrafStats Map Dashboard v3.1+ InfluxDBv2 WITH filter.json └── src/ ├── abuse_checker.py ├── config.py ├── geo_lookup.py ├── influx_writer.py ├── ip_classifier.py ├── log_parser.py ├── log_watcher.py ├── main.py ├── requirements.txt └── ua_parser_util.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ #Ignoring git and cache folders *.yml #Ignoring all the markdown and class files *.md #Ignore Map *.json ================================================ FILE: Dockerfile ================================================ FROM python:3.14-slim LABEL maintainer="npmgrafstats@smilebasti.de" RUN useradd --create-home --shell /bin/bash appuser && \ mkdir -p /data /home/appuser/app && \ chown -R appuser:appuser /data /home/appuser/app COPY src/requirements.txt /home/appuser/app/requirements.txt RUN pip install --no-cache-dir -r /home/appuser/app/requirements.txt COPY src/ /home/appuser/app/ RUN chown -R appuser:appuser /home/appuser/app USER appuser WORKDIR /home/appuser/app ENTRYPOINT ["python", "-u", "main.py"] ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. NginxproxymanagerGraf Copyright (C) 2023 Sebastian Wieser 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) 2023 Sebastian Wieser This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # npmGrafStats NginxProxyManager Grafana Statistics. This project analyzes the logs of the Nginx Proxy Manager and exports them to InfluxDB to be used in a Grafana Dashboard. npmGrafStats can save the Revers-Proxy and/or the Redirection Logs. Also a exclusion of IP's from for example external montitoring services is possible. [![current version](https://img.shields.io/docker/v/smilebasti/npmgrafstats/latest)](https://hub.docker.com/r/smilebasti/npmgrafstats) [![docker image size](https://img.shields.io/docker/image-size/smilebasti/npmgrafstats/latest)](https://hub.docker.com/r/smilebasti/npmgrafstats) [![docker pulls](https://img.shields.io/docker/pulls/smilebasti/npmgrafstats?color=%23099cec)](https://hub.docker.com/r/smilebasti/npmgrafstats) ### npmPlus If you are using npmPlus have a look at the branch: [npmPlus-main](https://github.com/smilebasti/npmGrafStats/tree/npmPlus-main) ### Following Data is extracted from the Logs: - source IP - target IP in your home network set in NPM - the targeted domain - the measurement time - the status code - the bytes transported - the Browser and OS - the Data of the source IP from GeoLite2-City.mmdb - Country - Coordinates - City A view of the Grafana Dashboard only within a few hours of running: ![npmGrafStats](https://user-images.githubusercontent.com/60941345/203383131-50b7197e-2e58-4bb1-a7e6-d92e15d3430a.png) ## Newest features v4.0.0 complete rewrite from shell scripts to a single threaded Python process. Massively reduces CPU and RAM usage especially with many log files. AbuseIPDB cache now uses SQLite (no more corruption). No breaking changes to ENV vars, volumes or Grafana dashboards. This project is a modified clone of https://github.com/Festeazy/nginxproxymanagerGraf and independent of https://github.com/jc21/nginx-proxy-manager. Changes to the original project can be found in the [changelog.md](https://github.com/smilebasti/npmGrafStats/blob/main/changelog.md) file. ### Obviously I'd appreciate any help or feedback :) Hope you enjoy. If you do so, please star this project. # Installation ### The Installation instructions can now be found in the [GitHub Wiki](https://github.com/smilebasti/npmGrafStats/wiki). Currently supported architectures: `amd64`, `arm/v7` and `arm64`. Github Registry is now additionally available to Docker Registry by adding `ghcr.io/` in front of `smilebasti/npmgrafstats:latest`. A full setup example is available with the [docker-compose.yml](https://github.com/smilebasti/npmGrafStats/blob/main/docker-compose.yml) ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=smilebasti/npmgrafstats&type=Date)](https://star-history.com/#smilebasti/npmgrafstats&Date) ================================================ FILE: changelog.md ================================================ # Changelog ### Not planned features - analyse fallback/default/error logs - grafana 10.1 missle map (route feature only one and not multiple possible) ## v4.0.0 - complete rewrite from shell scripts to Python with threading - 1 thread per logfile, persistent GeoIP readers + InfluxDB connection - SQLite WAL-mode cache for AbuseIPDB (replaces JSON, auto-migration) - compiled regex replaces grep/awk/cut subprocess chains - structured logging with Python logging module - graceful shutdown on SIGTERM/SIGINT - smaller Docker image (no bash, grepcidr, curl, gcc needed) - add LOG_LEVEL env var (default: INFO, supports DEBUG/WARNING/ERROR) - add VERBOSE_LOGGING env var (default: FALSE, logs every request like the original) - no breaking changes to ENV vars, volumes, measurements, tags, fields or Grafana dashboards ## v3.1.2 - update Readme - move maintainer lable to published image ## v3.1.1 - add major docker tag to avoid breacking change (ex. v3-arm) - cleanup ci build process and avoid seperate Docker-Arm File - remove arm version tags as they are not necessary for the build process anymore (latest-arm will continue) ## v3.1.0 - add the extraction of the Browser, Browser Version and OS - update Grafana Dashboard to show Bowser, Browser Version and OS (still missing) - add Supply chain attestations with Provenance attestations - use non root user - fixes Grafana ID: With Filter 18826 and No Filter 24693 ## v3.0.1 - fix grafana dashboard ## v3.0.0 - internal ipv6 (see #56 thanks @priyankub) - cache abuseipdb (see #56 thanks @priyankub) !Cache can corrupt if write is interupted. Run docker compose down before directly running docker compose up after pull! - add status code (see #53 thanks @gitwasi) - added lenght (transferd bytes) - added option to read Influx token and Abuseipdb key from a file (see #52 thanks @emerick-biron) - updated Grafana Dashboard ## v2.4.3 - make dockerfiles multi stage builds - add seperate Branch of npmPlusGrafStats (main and version) - fix #47 - handle if no ASN is found - add concurrent processing ## v2.4.2 - add cidr notation in monitoringips.txt file (see #45 thanks @pitbull) ## v2.4.1 - add AbuseIPDB check to container (not included in Grafana Dashboard, add manually) Thanks to @maxdd in #38 and #39 ## v2.4.0 - add ASN as optional feature see #32 and #33 thanks to @maxdd - added ASN to Grafana - added no filter Grafana Dashboard #20121 ## v2.3.2 - Grafana Dashboard added Filter - Fix spelling in Readme - add ghcr.io to documentation - add second Dockerfile for arm images as Dockerfile now uses python:3-slim and its not working with arm/v7 ## v2.3.1 - fix stop working after some time #2 (close client connection and use tail -F instaed of tail -f) - add github registry as alternative ghcr.io/smilebasti/npmgrafstats - add docker-compose restart: unless-stopped ## v2.3.0 - add arm/v7 and arm64/v8 image (see #11 and thanks to @Gyarbij with #12) - fix timezone issue (Thanks to Im1Random https://www.reddit.com/r/nginxproxymanager/comments/1418ae1/comment/jn0pizn/?) - create an option to see stats of internal domain-calls (see #14) (option INTERNAL_LOGS and MONITORING_LOGS see more in Installation wiki) - remove HOME_IPS to get IP automatically (see #15) - added a license - Grafana dashboard now uses the default bucket as source which gets set during the Grafana Influx datasource setup (see #14) - Grafana dashboard add Internal IPs , Montioring Ips count and other panels - Change Latitude and Longitude to latitude and longitude for easier future Grafana panels ## v2.2.1 - add option REDIRECTION_LOGS='ONLY' for only redirection logs analysis - add version to startup logs - add an external list of ip's to be excluded for exclusion of monitoring ip's - move HOME_IPS to internal domain ## v2.2.0 Removes duplicate logs of the same Connection in case of a restart of NpmGrafStats - add time to influx measurement (see #7) - convert [30/May/2023:14:16:48 +0000] to 2009-11-10T23:00:00.123456Z RFC 3339 - Timezone is not converted! Stays UTC ## v2.1.1 - fix redirection logs - added Redirections and ReverseProxy Dashboard to Grafana - fix Readme.md - New Grafana ID 18826 (i accidentally the old one. Sorry) ## v2.1.0 - clean up Dockerfile - print and set measurment name - print 'data send' after influx send - added sendredirectionips.sh for redirection logs (see #5) - true statement for redirection logs - removed NPMGRAF_HOME variable - changed docker naming sheme to version number - added internal-ip filter - changed from sh to bash to use regex ## v2.0.0 ### Dev info/changes made to original To the Original Project following changes were made: - the new log format and only the proxy-host*-access.log from NPM are used - Domains now allow a "-" in the domain - no subdomains or subdomains up to 3 levels extra (sub.sub.sub.domain.tld) - the targeted internal ip is logged - using influxdb v2 #### Detailed - args parssed sendips.sh to Getipinfo.py: 1. Outside IP 2. Domain 3. length 4. Target IP - These Domain only registered for me : .env.de, config.php.com(.de,.org) - Add Domains to Dashboard - Did NPM change the log format? -> to access.log - exclude external Ip - add apk grep for --line-buffered as not included in bash in busybox -> overflow -> process stopped - upgrade to influx 2 - see project https://github.com/evijayan2/nginxproxymanagerGraf ================================================ FILE: docker-compose.yml ================================================ services: npm: image: 'jc21/nginx-proxy-manager:latest' restart: unless-stopped ports: # These ports are in format : - '80:80' # Public HTTP Port - '443:443' # Public HTTPS Port - '81:81' # Admin Web Port # Add any other Stream port you want to expose # - '21:21' # FTP environment: # Mysql/Maria connection parameters: DB_MYSQL_HOST: "db" DB_MYSQL_PORT: 3306 DB_MYSQL_USER: "npm" DB_MYSQL_PASSWORD: "npm" DB_MYSQL_NAME: "npm" # Uncomment this if IPv6 is not enabled on your host # DISABLE_IPV6: 'true' volumes: - ./data:/data - ./letsencrypt:/etc/letsencrypt depends_on: - db db: image: 'jc21/mariadb-aria:latest' restart: unless-stopped environment: MYSQL_ROOT_PASSWORD: 'npm' MYSQL_DATABASE: 'npm' MYSQL_USER: 'npm' MYSQL_PASSWORD: 'npm' volumes: - ./mysql:/var/lib/mysql npmgraf: image: smilebasti/npmgrafstats:latest # image: ghcr.io/smilebasti/npmgrafstats:latest # if you prefer Github Container Registry restart: unless-stopped environment: REDIRECTION_LOGS: '' # TRUE or FALSE or ONLY INTERNAL_LOGS: '' # see Github wiki for more information MONITORING_LOGS: '' # see Github wiki for more information INFLUX_HOST: 'http://influxdb:8086' # use host IP if necessary INFLUX_BUCKET: 'npmgrafstats' INFLUX_ORG: 'npmgrafstats' INFLUX_TOKEN: '' # REQUIRED: insert or add to ./npmgraf_data/influxdb-token.txt after manual Influxdb bucket token creation # ABUSEIP_KEY: '' # optional: insert or add to ./npmgraf_data/abuseipdb-key.txt # LOG_LEVEL: 'DEBUG' # optional: DEBUG, INFO (default), WARNING, ERROR # VERBOSE_LOGGING: 'TRUE' # optional: log every request like the original shell scripts volumes: - ./data/logs:/logs - ./geolite:/geolite - ./npmgraf_data:/data depends_on: - geoipupdate - npm influxdb: image: influxdb:2.9-alpine restart: unless-stopped environment: DOCKER_INFLUXDB_INIT_MODE: 'setup' DOCKER_INFLUXDB_INIT_USERNAME: '' DOCKER_INFLUXDB_INIT_PASSWORD: '' # atleast 8 characters DOCKER_INFLUXDB_INIT_ORG: 'npmgrafstats' DOCKER_INFLUXDB_INIT_BUCKET: 'npmgrafstats' volumes: # Mount for influxdb data directory and configuration - ./influxdbv2:/var/lib/influxdb2 ports: - '8086:8086' geoipupdate: image: maxmindinc/geoipupdate restart: unless-stopped environment: GEOIPUPDATE_ACCOUNT_ID: '' GEOIPUPDATE_LICENSE_KEY: '' GEOIPUPDATE_EDITION_IDS: 'GeoLite2-City GeoLite2-ASN' #GeoLite2-ASN is optional GEOIPUPDATE_FREQUENCY: 24 volumes: - ./geolite:/usr/share/GeoIP portainer: image: portainer/portainer-ce:latest restart: always ports: - '8000:8000' - '9000:9000' - '9443:9443' volumes: - /var/run/docker.sock:/var/run/docker.sock - ./portainer_data:/data grafana: image: grafana/grafana-oss restart: unless-stopped ports: - '3000:3000' volumes: - ./grafana-storage:/var/lib/grafana # after start: sudo chown 472:472 grafana-storage ================================================ FILE: npmGrafStats Map Dashboard v3.1+ InfluxDBv2 NO filter.json ================================================ { "__inputs": [ { "name": "DS_INFLUXDB-NPMGRAFSTATS", "label": "influxdb-npmgrafstats", "description": "", "type": "datasource", "pluginId": "influxdb", "pluginName": "InfluxDB" } ], "__elements": {}, "__requires": [ { "type": "panel", "id": "bargauge", "name": "Bar gauge", "version": "" }, { "type": "panel", "id": "geomap", "name": "Geomap", "version": "" }, { "type": "grafana", "id": "grafana", "name": "Grafana", "version": "12.3.1" }, { "type": "datasource", "id": "influxdb", "name": "InfluxDB", "version": "1.0.0" }, { "type": "panel", "id": "piechart", "name": "Pie chart", "version": "" }, { "type": "panel", "id": "stat", "name": "Stat", "version": "" }, { "type": "panel", "id": "table", "name": "Table", "version": "" }, { "type": "panel", "id": "timeseries", "name": "Time series", "version": "" } ], "annotations": { "list": [ { "builtIn": 1, "datasource": { "type": "datasource", "uid": "grafana" }, "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "target": { "limit": 100, "matchAny": false, "tags": [], "type": "dashboard" }, "type": "dashboard" } ] }, "description": "npmGrafStats Map Dashboard with InfluxDB powered by https://github.com/smilebasti/npmGrafStats\n\nFor a Dashboard with the filtering option use https://grafana.com/grafana/dashboards/18826", "editable": true, "fiscalYearStartMonth": 0, "graphTooltip": 0, "links": [], "panels": [ { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 }, "id": 23, "panels": [], "title": "Overview (without monitoring services or internal calls)", "type": "row" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "description": "(without monitoring services or internal calls)", "fieldConfig": { "defaults": { "color": { "mode": "continuous-GrYlRd" }, "displayName": "${__field.labels.__values}", "mappings": [], "noValue": "No Domain called", "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 17, "w": 24, "x": 0, "y": 1 }, "id": 11, "options": { "displayMode": "lcd", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 10, "minVizWidth": 0, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "limit": 100, "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "Domain" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r._field == \"Domain\")\r\n |> group(columns: [\"Domain\"])\r\n |> count()\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "Domain" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "title": "All real Accessed Domains", "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "custom": { "align": "center", "cellOptions": { "type": "auto" }, "filterable": false, "footer": { "reducers": [] }, "inspect": false }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [ { "matcher": { "id": "byName", "options": "_value" }, "properties": [ { "id": "displayName", "value": "Count" } ] } ] }, "gridPos": { "h": 8, "w": 7, "x": 0, "y": 18 }, "id": 26, "options": { "cellHeight": "sm", "enablePagination": false, "frameIndex": 5, "showHeader": true, "sortBy": [ { "desc": true, "displayName": "Count" } ] }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "IP" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"_field\"] == \"IP\") \r\n |> group(columns: [\"IP\"])\r\n |> count()\r\n |> drop(columns: [\"_start\", \"_stop\"])\r\n |> yield(name: \"alias\")\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "IP" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "title": "Hits per IP", "transformations": [ { "id": "labelsToFields", "options": { "mode": "columns" } }, { "id": "merge", "options": {} }, { "id": "joinByField", "options": { "byField": "IP", "mode": "outer" } } ], "type": "table" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "description": "(without monitoring services or internal calls)", "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 8, "w": 5, "x": 7, "y": 18 }, "id": 25, "options": { "colorMode": "value", "graphMode": "area", "justifyMode": "auto", "orientation": "auto", "percentChangeColorMode": "standard", "reduceOptions": { "calcs": [ "sum" ], "fields": "", "values": false }, "showPercentChange": false, "textMode": "auto", "wideLayout": true }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "1m" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r._field == \"IP\")\r\n |> group(columns: [\"_count\"])\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n |> count()", "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "IP" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "timeFrom": "5m", "title": "Hit's in the last ...", "type": "stat" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "description": "(without monitoring services or internal calls)", "fieldConfig": { "defaults": { "color": { "mode": "continuous-GrYlRd" }, "displayName": "${__field.labels.__values}", "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 22, "w": 12, "x": 12, "y": 18 }, "id": 24, "options": { "displayMode": "basic", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 10, "minVizWidth": 0, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [], "fields": "/.*/", "limit": 220, "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "alias": "", "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "name" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r._field == \"Name\")\r\n |> group(columns: [\"Name\"])\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n |> count()", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "name" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [], "tz": "" } ], "title": "Hits per Nation", "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "fixedColor": "yellow", "mode": "palette-classic" }, "custom": { "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text", "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6, "drawStyle": "line", "fillOpacity": 13, "gradientMode": "opacity", "hideFrom": { "legend": false, "tooltip": false, "viz": false }, "insertNulls": false, "lineInterpolation": "linear", "lineStyle": { "fill": "solid" }, "lineWidth": 1, "pointSize": 3, "scaleDistribution": { "type": "linear" }, "showPoints": "always", "showValues": false, "spanNulls": false, "stacking": { "group": "A", "mode": "none" }, "thresholdsStyle": { "mode": "off" } }, "mappings": [], "thresholds": { "mode": "percentage", "steps": [ { "color": "green", "value": 0 }, { "color": "yellow", "value": 75 }, { "color": "dark-red", "value": 90 } ] } }, "overrides": [ { "__systemRef": "hideSeriesFrom", "matcher": { "id": "byNames", "options": { "mode": "exclude", "names": [ "Domain" ], "prefix": "All except:", "readOnly": true } }, "properties": [ { "id": "custom.hideFrom", "value": { "legend": false, "tooltip": true, "viz": true } } ] } ] }, "gridPos": { "h": 14, "w": 12, "x": 0, "y": 26 }, "id": 27, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "hideZeros": false, "mode": "multi", "sort": "asc" } }, "pluginVersion": "12.3.1", "targets": [ { "alias": "", "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "1m" ], "type": "time" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"_field\"] == \"Domain\")\r\n |> group(columns: [\"_measurement\", \"_field\", \"_time=1m\"])\r\n |> aggregateWindow(every: 1m, fn: count, createEmpty: false)\r\n |> yield(name: \"count\")\r\n\r\n\r\n", "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "Domain" ], "type": "field" }, { "params": [], "type": "count" }, { "params": [ "alias" ], "type": "alias" } ] ], "tags": [], "tz": "" } ], "title": "Hits per 1 min", "type": "timeseries" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "continuous-GrYlRd" }, "displayName": "${__field.labels.__values}", "mappings": [], "noValue": "No Domain called", "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 12, "w": 12, "x": 0, "y": 40 }, "id": 31, "options": { "displayMode": "lcd", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 10, "minVizWidth": 0, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "limit": 100, "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "Domain" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r._field == \"Domain\")\r\n |> group(columns: [\"Domain\"])\r\n |> count()\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "Domain" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "title": "Real Reverse Proxy Domains", "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "continuous-GrYlRd" }, "displayName": "${__field.labels.__values}", "mappings": [], "noValue": "No Redirect Domain called", "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 12, "w": 12, "x": 12, "y": 40 }, "id": 32, "options": { "displayMode": "lcd", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 10, "minVizWidth": 0, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "limit": 50, "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "Domain" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\")\r\n |> filter(fn: (r) => r._field == \"Domain\")\r\n |> group(columns: [\"Domain\"])\r\n |> count()\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "Domain" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "title": "Real Redirection Domains", "type": "bargauge" }, { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 52 }, "id": 19, "panels": [], "title": "World Map", "type": "row" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "fixedColor": "#c94141", "mode": "thresholds" }, "custom": { "hideFrom": { "legend": false, "tooltip": false, "viz": false } }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "semi-dark-red", "value": 0 }, { "color": "semi-dark-yellow", "value": 4 }, { "color": "#3ce126", "value": 10 } ] }, "unit": "none" }, "overrides": [ { "matcher": { "id": "byName", "options": "_value" }, "properties": [ { "id": "displayName", "value": "Count" } ] } ] }, "gridPos": { "h": 21, "w": 24, "x": 0, "y": 53 }, "id": 33, "maxDataPoints": 1, "options": { "basemap": { "config": {}, "name": "Layer 0", "noRepeat": false, "type": "default" }, "controls": { "mouseWheelZoom": true, "showAttribution": true, "showDebug": false, "showMeasure": false, "showScale": false, "showZoom": true }, "layers": [ { "config": { "showLegend": true, "style": { "color": { "field": "_value", "fixed": "dark-green" }, "opacity": 0.9, "rotation": { "field": "_value", "fixed": 0, "max": 360, "min": -360, "mode": "mod" }, "size": { "field": "_value", "fixed": 5, "max": 14, "min": 2 }, "symbol": { "fixed": "img/icons/marker/circle.svg", "mode": "fixed" }, "text": { "fixed": "", "mode": "field" }, "textConfig": { "fontSize": 12, "offsetX": 0, "offsetY": 0, "textAlign": "center", "textBaseline": "middle" } } }, "location": { "mode": "auto" }, "name": "IP count", "tooltip": true, "type": "markers" } ], "tooltip": { "mode": "details" }, "view": { "allLayers": true, "id": "fit", "lat": 0, "lon": 0, "noRepeat": false, "zoom": 14.94 } }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "latitude" ], "type": "tag" }, { "params": [ "longitude" ], "type": "tag" }, { "params": [ "IP" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r._field == \"IP\") \r\n |> group(columns: [\"longitude\",\"latitude\",\"IP\"])\r\n |> count()\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "IP" ], "type": "field" }, { "params": [], "type": "count" }, { "params": [ "counts" ], "type": "alias" } ] ], "tags": [] } ], "title": "Real IPs Map Overview (without excluded IPs)", "transformations": [ { "id": "labelsToFields", "options": {} }, { "id": "merge", "options": {} }, { "id": "joinByField", "options": { "byField": "IP", "mode": "outer" } } ], "type": "geomap" }, { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 74 }, "id": 45, "panels": [], "title": "Browser and Data", "type": "row" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "mappings": [], "thresholds": { "mode": "percentage", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] }, "unit": "decbytes" }, "overrides": [] }, "gridPos": { "h": 8, "w": 8, "x": 0, "y": 75 }, "id": 42, "options": { "displayMode": "gradient", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 16, "minVizWidth": 8, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "allValues" ], "fields": "", "limit": 10, "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r[\"_field\"] == \"length\")\n |> group(columns: [\"Domain\"])\n |> sum()\n |> group()\n |> sort(desc: true)\n |> limit(n: 10)\n \n ", "refId": "A" } ], "title": "Data (lenght) transmitted per Domain (Top 10)", "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "description": " ", "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "hideFrom": { "legend": false, "tooltip": false, "viz": false } }, "displayName": "${__field.labels.__values}", "mappings": [], "unit": "none" }, "overrides": [] }, "gridPos": { "h": 8, "w": 8, "x": 8, "y": 75 }, "id": 43, "options": { "displayLabels": [ "name" ], "legend": { "displayMode": "list", "placement": "right", "showLegend": true, "values": [ "percent" ] }, "pieType": "pie", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": false }, "sort": "desc", "tooltip": { "hideZeros": false, "mode": "single", "sort": "none" } }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r[\"_field\"] == \"statuscode\")\n |> duplicate(column: \"_value\", as: \"new_column\")\n |> group(columns: [\"new_column\"])\n |> count()\n |> yield(name: \"alias\")", "refId": "A" } ], "title": "Statuscode distribution", "type": "piechart" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "hideFrom": { "legend": false, "tooltip": false, "viz": false } }, "displayName": "score: ${__field.labels.__values}", "mappings": [] }, "overrides": [] }, "gridPos": { "h": 8, "w": 8, "x": 16, "y": 75 }, "id": 44, "options": { "displayLabels": [ "name" ], "legend": { "displayMode": "list", "placement": "right", "showLegend": true, "values": [ "percent" ] }, "pieType": "pie", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": false }, "sort": "desc", "tooltip": { "hideZeros": false, "mode": "single", "sort": "none" } }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r[\"_field\"] == \"abuseConfidenceScore\")\n |> group(columns: [\"_measurement\", \"abuseConfidenceScore\"])\n |> count()\n |> drop(columns: [\"_start\", \"_stop\"])", "refId": "A" } ], "title": "AbuseIpDB Confidence Score", "type": "piechart" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "displayName": "${__field.labels.__values}", "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [ { "matcher": { "id": "byName", "options": "" }, "properties": [] } ] }, "gridPos": { "h": 10, "w": 8, "x": 0, "y": 83 }, "id": 46, "options": { "displayMode": "gradient", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 16, "minVizWidth": 8, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": false }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r._field == \"browser\")\n |> duplicate(column: \"_value\", as: \"browser\")\n |> group(columns: [\"browser\"])\n |> count()\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\n \n", "refId": "A" } ], "title": "Browsers", "transformations": [ { "id": "reduce", "options": { "reducers": [ "lastNotNull" ] } }, { "id": "sortBy", "options": { "fields": {}, "sort": [ { "desc": true, "field": "Last *" } ] } }, { "id": "rowsToFields", "options": {} }, { "id": "renameByRegex", "options": { "regex": "^_value(.*)$", "renamePattern": "$1" } } ], "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "hideFrom": { "legend": false, "tooltip": false, "viz": false } }, "displayName": "${__field.labels.__values}", "mappings": [] }, "overrides": [] }, "gridPos": { "h": 10, "w": 8, "x": 8, "y": 83 }, "id": 48, "options": { "legend": { "displayMode": "list", "placement": "right", "showLegend": true, "values": [ "percent" ] }, "pieType": "pie", "reduceOptions": { "calcs": [ "max" ], "fields": "", "limit": 100, "values": false }, "sort": "desc", "tooltip": { "hideZeros": false, "mode": "single", "sort": "none" } }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r._field == \"browser_version\")\n |> duplicate(column: \"_value\", as: \"browser_version\")\n |> group(columns: [\"browser_version\"])\n |> count()\n |> top(n: 10)\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])", "refId": "A" } ], "title": "Browser Version", "type": "piechart" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "displayName": "${__field.labels.__values}", "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 10, "w": 8, "x": 16, "y": 83 }, "id": 47, "options": { "displayMode": "gradient", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 16, "minVizWidth": 8, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": false }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r._field == \"os\")\n |> duplicate(column: \"_value\", as: \"os\")\n |> group(columns: [\"os\"])\n |> count()\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\n \n", "refId": "A" } ], "title": "OS", "type": "bargauge" }, { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 93 }, "id": 37, "panels": [], "title": "ASN", "type": "row" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "custom": { "align": "center", "cellOptions": { "type": "auto" }, "footer": { "reducers": [] }, "inspect": false }, "displayName": "${__field.labels.__values}", "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [ { "matcher": { "id": "byName", "options": "_value" }, "properties": [ { "id": "displayName", "value": "Count" } ] } ] }, "gridPos": { "h": 9, "w": 24, "x": 0, "y": 94 }, "id": 39, "options": { "cellHeight": "sm", "frameIndex": 1, "showHeader": true, "sortBy": [ { "desc": true, "displayName": "Count" } ] }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"_field\"] == \"Asn\") \r\n |> group(columns: [\"Asn\"])\r\n |> count()\r\n |> drop(columns: [\"_start\", \"_stop\"])\r\n |> yield(name: \"alias\")", "refId": "A" } ], "title": "ASN", "transformations": [ { "id": "labelsToFields", "options": {} }, { "id": "merge", "options": {} } ], "type": "table" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "custom": { "align": "center", "cellOptions": { "type": "auto" }, "footer": { "reducers": [] }, "inspect": false }, "displayName": "${__field.labels.__values}", "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [ { "matcher": { "id": "byName", "options": "_value" }, "properties": [ { "id": "displayName", "value": "Count" } ] } ] }, "gridPos": { "h": 9, "w": 24, "x": 0, "y": 103 }, "id": 38, "options": { "cellHeight": "sm", "frameIndex": 1, "showHeader": true, "sortBy": [ { "desc": true, "displayName": "Count" } ] }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"_field\"] == \"Asn\") \r\n |> group(columns: [\"Asn\", \"IP\"])\r\n |> count()\r\n |> drop(columns: [\"_start\", \"_stop\"])\r\n |> yield(name: \"alias\")", "refId": "A" } ], "title": "ASN (per IP)", "transformations": [ { "id": "labelsToFields", "options": {} }, { "id": "merge", "options": {} } ], "type": "table" } ], "preload": false, "refresh": "15s", "schemaVersion": 42, "tags": [], "templating": { "list": [] }, "time": { "from": "now-6h", "to": "now" }, "timepicker": { "refresh_intervals": [ "5s", "10s", "15s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d" ] }, "timezone": "", "title": "npmGrafStats Map Dashboard v3.1+ InfluxDBv2 NO filter", "uid": "pvWDTV_MW1", "version": 8, "weekStart": "", "id": null } ================================================ FILE: npmGrafStats Map Dashboard v3.1+ InfluxDBv2 WITH filter.json ================================================ { "__inputs": [ { "name": "DS_INFLUXDB-NPMGRAFSTATS", "label": "influxdb-npmgrafstats", "description": "", "type": "datasource", "pluginId": "influxdb", "pluginName": "InfluxDB" } ], "__elements": {}, "__requires": [ { "type": "panel", "id": "bargauge", "name": "Bar gauge", "version": "" }, { "type": "panel", "id": "geomap", "name": "Geomap", "version": "" }, { "type": "grafana", "id": "grafana", "name": "Grafana", "version": "12.3.1" }, { "type": "datasource", "id": "influxdb", "name": "InfluxDB", "version": "1.0.0" }, { "type": "panel", "id": "piechart", "name": "Pie chart", "version": "" }, { "type": "panel", "id": "stat", "name": "Stat", "version": "" }, { "type": "panel", "id": "table", "name": "Table", "version": "" }, { "type": "panel", "id": "timeseries", "name": "Time series", "version": "" } ], "annotations": { "list": [ { "builtIn": 1, "datasource": { "type": "datasource", "uid": "grafana" }, "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "target": { "limit": 100, "matchAny": false, "tags": [], "type": "dashboard" }, "type": "dashboard" } ] }, "description": "npmGrafStats Map Dashboard with InfluxDBv2 powered by https://github.com/smilebasti/npmGrafStats\n\nFor a Dashboard WITHOUT the filtering option use https://grafana.com/grafana/dashboards/24693", "editable": true, "fiscalYearStartMonth": 0, "graphTooltip": 0, "links": [], "panels": [ { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 }, "id": 23, "panels": [], "title": "Overview (without monitoring services or internal calls)", "type": "row" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "description": "(without monitoring services or internal calls)", "fieldConfig": { "defaults": { "color": { "mode": "continuous-GrYlRd" }, "displayName": "${__field.labels.__values}", "mappings": [], "noValue": "No Domain called", "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 17, "w": 24, "x": 0, "y": 1 }, "id": 11, "options": { "displayMode": "lcd", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 10, "minVizWidth": 0, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "limit": 50, "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "Domain" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r._field == \"Domain\")\r\n |> group(columns: [\"Domain\"])\r\n |> count()\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "Domain" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "title": "All real Accessed Domains", "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "custom": { "align": "center", "cellOptions": { "type": "auto" }, "filterable": false, "footer": { "reducers": [] }, "inspect": false }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [ { "matcher": { "id": "byName", "options": "_value" }, "properties": [ { "id": "displayName", "value": "Count" } ] } ] }, "gridPos": { "h": 8, "w": 7, "x": 0, "y": 18 }, "id": 26, "options": { "cellHeight": "sm", "enablePagination": false, "frameIndex": 5, "showHeader": true, "sortBy": [ { "desc": true, "displayName": "Count" } ] }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "IP" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r[\"_field\"] == \"IP\") \r\n |> group(columns: [\"IP\"])\r\n |> count()\r\n |> drop(columns: [\"_start\", \"_stop\"])\r\n |> yield(name: \"alias\")\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "IP" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "title": "Hits per IP", "transformations": [ { "id": "labelsToFields", "options": { "mode": "columns" } }, { "id": "merge", "options": {} }, { "id": "joinByField", "options": { "byField": "IP", "mode": "outer" } } ], "type": "table" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "description": "(without monitoring services or internal calls)", "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 8, "w": 5, "x": 7, "y": 18 }, "id": 25, "options": { "colorMode": "value", "graphMode": "area", "justifyMode": "auto", "orientation": "auto", "percentChangeColorMode": "standard", "reduceOptions": { "calcs": [ "sum" ], "fields": "", "values": false }, "showPercentChange": false, "textMode": "auto", "wideLayout": true }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "1m" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r._field == \"IP\")\r\n |> group(columns: [\"_count\"])\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n |> count()", "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "IP" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "timeFrom": "5m", "title": "Hit's in the last ...", "type": "stat" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "description": "(without monitoring services or internal calls)", "fieldConfig": { "defaults": { "color": { "mode": "continuous-GrYlRd" }, "displayName": "${__field.labels.__values}", "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 22, "w": 12, "x": 12, "y": 18 }, "id": 24, "options": { "displayMode": "basic", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 10, "minVizWidth": 0, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [], "fields": "/.*/", "limit": 220, "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "alias": "", "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "name" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r._field == \"Name\")\r\n |> group(columns: [\"Name\"])\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n |> count()", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "name" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [], "tz": "" } ], "title": "Hits per Nation", "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "fixedColor": "yellow", "mode": "palette-classic" }, "custom": { "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text", "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6, "drawStyle": "line", "fillOpacity": 13, "gradientMode": "opacity", "hideFrom": { "legend": false, "tooltip": false, "viz": false }, "insertNulls": false, "lineInterpolation": "linear", "lineStyle": { "fill": "solid" }, "lineWidth": 1, "pointSize": 3, "scaleDistribution": { "type": "linear" }, "showPoints": "always", "showValues": false, "spanNulls": false, "stacking": { "group": "A", "mode": "none" }, "thresholdsStyle": { "mode": "off" } }, "mappings": [], "thresholds": { "mode": "percentage", "steps": [ { "color": "green", "value": 0 }, { "color": "yellow", "value": 75 }, { "color": "dark-red", "value": 90 } ] } }, "overrides": [ { "__systemRef": "hideSeriesFrom", "matcher": { "id": "byNames", "options": { "mode": "exclude", "names": [ "Domain" ], "prefix": "All except:", "readOnly": true } }, "properties": [ { "id": "custom.hideFrom", "value": { "legend": false, "tooltip": true, "viz": true } } ] } ] }, "gridPos": { "h": 14, "w": 12, "x": 0, "y": 26 }, "id": 27, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "hideZeros": false, "mode": "multi", "sort": "asc" } }, "pluginVersion": "12.3.1", "targets": [ { "alias": "", "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "1m" ], "type": "time" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r[\"_field\"] == \"Domain\")\r\n |> group(columns: [\"_measurement\", \"_field\", \"_time=1m\"])\r\n |> aggregateWindow(every: 1m, fn: count, createEmpty: false)\r\n |> yield(name: \"count\")\r\n\r\n\r\n", "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "Domain" ], "type": "field" }, { "params": [], "type": "count" }, { "params": [ "alias" ], "type": "alias" } ] ], "tags": [], "tz": "" } ], "title": "Hits per 1 min", "type": "timeseries" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "continuous-GrYlRd" }, "displayName": "${__field.labels.__values}", "mappings": [], "noValue": "No Domain called", "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 12, "w": 12, "x": 0, "y": 40 }, "id": 31, "options": { "displayMode": "lcd", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 10, "minVizWidth": 0, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "limit": 50, "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "Domain" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r._field == \"Domain\")\r\n |> group(columns: [\"Domain\"])\r\n |> count()\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "Domain" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "title": "Real Reverse Proxy Domains", "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "continuous-GrYlRd" }, "displayName": "${__field.labels.__values}", "mappings": [], "noValue": "No Redirect Domain called", "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 12, "w": 12, "x": 12, "y": 40 }, "id": 32, "options": { "displayMode": "lcd", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 10, "minVizWidth": 0, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "limit": 50, "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "Domain" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r._field == \"Domain\")\r\n |> group(columns: [\"Domain\"])\r\n |> count()\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "Domain" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "title": "Real Redirection Domains", "type": "bargauge" }, { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 52 }, "id": 19, "panels": [], "title": "World Map", "type": "row" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "fixedColor": "#c94141", "mode": "thresholds" }, "custom": { "hideFrom": { "legend": false, "tooltip": false, "viz": false } }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "semi-dark-red", "value": 0 }, { "color": "semi-dark-yellow", "value": 4 }, { "color": "#3ce126", "value": 10 } ] }, "unit": "none" }, "overrides": [ { "matcher": { "id": "byName", "options": "_value" }, "properties": [ { "id": "displayName", "value": "Count" } ] } ] }, "gridPos": { "h": 21, "w": 24, "x": 0, "y": 53 }, "id": 33, "maxDataPoints": 1, "options": { "basemap": { "config": {}, "name": "Layer 0", "type": "default" }, "controls": { "mouseWheelZoom": true, "showAttribution": true, "showDebug": false, "showMeasure": false, "showScale": false, "showZoom": true }, "layers": [ { "config": { "showLegend": true, "style": { "color": { "field": "_value", "fixed": "dark-green" }, "opacity": 0.6, "rotation": { "field": "_value", "fixed": 0, "max": 360, "min": -360, "mode": "mod" }, "size": { "field": "_value", "fixed": 5, "max": 14, "min": 2 }, "symbol": { "fixed": "img/icons/marker/circle.svg", "mode": "fixed" }, "text": { "fixed": "", "mode": "field" }, "textConfig": { "fontSize": 12, "offsetX": 0, "offsetY": 0, "textAlign": "center", "textBaseline": "middle" } } }, "location": { "mode": "auto" }, "name": "IP count", "tooltip": true, "type": "markers" } ], "tooltip": { "mode": "details" }, "view": { "allLayers": true, "id": "fit", "lat": 0, "lon": 0, "noRepeat": false, "zoom": 14.94 } }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "groupBy": [ { "params": [ "latitude" ], "type": "tag" }, { "params": [ "longitude" ], "type": "tag" }, { "params": [ "IP" ], "type": "tag" } ], "measurement": "ReverseProxyConnections", "orderByTime": "ASC", "policy": "default", "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r._field == \"IP\") \r\n |> group(columns: [\"longitude\",\"latitude\",\"IP\"])\r\n |> count()\r\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\r\n\r\n", "refId": "A", "resultFormat": "table", "select": [ [ { "params": [ "IP" ], "type": "field" }, { "params": [], "type": "count" }, { "params": [ "counts" ], "type": "alias" } ] ], "tags": [] } ], "title": "Real IPs Map Overview (without excluded IPs)", "transformations": [ { "id": "labelsToFields", "options": {} }, { "id": "merge", "options": {} }, { "id": "joinByField", "options": { "byField": "IP", "mode": "outer" } } ], "type": "geomap" }, { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 74 }, "id": 43, "panels": [], "title": "Browser and Data", "type": "row" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "mappings": [], "thresholds": { "mode": "percentage", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] }, "unit": "decbytes" }, "overrides": [] }, "gridPos": { "h": 8, "w": 8, "x": 0, "y": 75 }, "id": 40, "options": { "displayMode": "gradient", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 16, "minVizWidth": 8, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": true }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\n |> filter(fn: (r) => r[\"_field\"] == \"length\")\n |> group(columns: [\"Domain\"])\n |> sum()\n |> group()\n |> sort(desc: true)\n |> limit(n: 10)\n ", "refId": "A" } ], "title": "Data (lenght) transmitted per Domain (Top 10)", "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "hideFrom": { "legend": false, "tooltip": false, "viz": false } }, "displayName": "${__field.labels.__values}", "mappings": [] }, "overrides": [] }, "gridPos": { "h": 8, "w": 8, "x": 8, "y": 75 }, "id": 41, "options": { "displayLabels": [ "name" ], "legend": { "displayMode": "list", "placement": "right", "showLegend": true, "values": [ "percent" ] }, "pieType": "pie", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": false }, "sort": "desc", "tooltip": { "hideZeros": false, "mode": "single", "sort": "none" } }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\n |> filter(fn: (r) => r[\"_field\"] == \"statuscode\")\n |> duplicate(column: \"_value\", as: \"new_column\")\n |> group(columns: [\"new_column\"])\n |> count()\n |> yield(name: \"alias\")", "refId": "A" } ], "title": "Statuscode distribution", "type": "piechart" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "hideFrom": { "legend": false, "tooltip": false, "viz": false } }, "displayName": "score: ${__field.labels.__values}", "mappings": [] }, "overrides": [] }, "gridPos": { "h": 8, "w": 8, "x": 16, "y": 75 }, "id": 42, "options": { "displayLabels": [ "name" ], "legend": { "displayMode": "list", "placement": "right", "showLegend": true, "values": [ "percent" ] }, "pieType": "pie", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": false }, "sort": "desc", "tooltip": { "hideZeros": false, "mode": "single", "sort": "none" } }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\n |> filter(fn: (r) => r[\"_field\"] == \"abuseConfidenceScore\")\n |> group(columns: [\"_measurement\", \"abuseConfidenceScore\"])\n |> count()\n |> drop(columns: [\"_start\", \"_stop\"])", "refId": "A" } ], "title": "AbuseIpDB Confidence Score", "type": "piechart" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 10, "w": 8, "x": 0, "y": 83 }, "id": 44, "options": { "displayMode": "gradient", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 16, "minVizWidth": 8, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": false }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\n |> filter(fn: (r) => r._field == \"browser\")\n |> duplicate(column: \"_value\", as: \"browser\")\n |> group(columns: [\"browser\"])\n |> count()\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\n \n\n ", "refId": "A" } ], "title": "Browser", "transformations": [ { "id": "reduce", "options": { "reducers": [ "lastNotNull" ] } }, { "id": "sortBy", "options": { "fields": {}, "sort": [ { "desc": true, "field": "Last *" } ] } }, { "id": "rowsToFields", "options": {} }, { "id": "renameByRegex", "options": { "regex": "^_value(.*)$", "renamePattern": "$1" } } ], "type": "bargauge" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "hideFrom": { "legend": false, "tooltip": false, "viz": false } }, "displayName": "${__field.labels.__values}", "mappings": [] }, "overrides": [] }, "gridPos": { "h": 10, "w": 8, "x": 8, "y": 83 }, "id": 45, "options": { "legend": { "displayMode": "list", "placement": "right", "showLegend": true, "values": [ "percent" ] }, "pieType": "pie", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": false }, "sort": "desc", "tooltip": { "hideZeros": false, "mode": "single", "sort": "none" } }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\n |> filter(fn: (r) => r._field == \"browser_version\")\n |> duplicate(column: \"_value\", as: \"browser_version\")\n |> group(columns: [\"browser_version\"])\n |> count()\n |> top(n: 10)\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])", "refId": "A" } ], "title": "Browser Version", "type": "piechart" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "displayName": "${__field.labels.__values}", "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 10, "w": 8, "x": 16, "y": 83 }, "id": 46, "options": { "displayMode": "gradient", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": false }, "maxVizHeight": 300, "minVizHeight": 16, "minVizWidth": 8, "namePlacement": "auto", "orientation": "horizontal", "reduceOptions": { "calcs": [ "lastNotNull" ], "fields": "", "values": false }, "showUnfilled": true, "sizing": "auto", "valueMode": "color" }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\n |> filter(fn: (r) => r._field == \"os\")\n |> duplicate(column: \"_value\", as: \"os\")\n |> group(columns: [\"os\"])\n |> count()\n |> drop(columns: [\"host\", \"_field\", \"_measurement\", \"_start\", \"_stop\"])\n ", "refId": "A" } ], "title": "OS", "type": "bargauge" }, { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 93 }, "id": 37, "panels": [], "title": "ASN", "type": "row" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "custom": { "align": "center", "cellOptions": { "type": "auto" }, "footer": { "reducers": [] }, "inspect": false }, "displayName": "${__field.labels.__values}", "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [ { "matcher": { "id": "byName", "options": "_value" }, "properties": [ { "id": "displayName", "value": "Count" } ] } ] }, "gridPos": { "h": 9, "w": 24, "x": 0, "y": 94 }, "id": 38, "options": { "cellHeight": "sm", "frameIndex": 1, "showHeader": true, "sortBy": [ { "desc": true, "displayName": "Count" } ] }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r[\"_field\"] == \"Asn\") \r\n |> group(columns: [\"Asn\", \"IP\"])\r\n |> count()\r\n |> drop(columns: [\"_start\", \"_stop\"])\r\n |> yield(name: \"alias\")", "refId": "A" } ], "title": "ASN", "transformations": [ { "id": "labelsToFields", "options": {} }, { "id": "merge", "options": {} } ], "type": "table" }, { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "fieldConfig": { "defaults": { "custom": { "align": "center", "cellOptions": { "type": "auto" }, "footer": { "reducers": [] }, "inspect": false }, "displayName": "${__field.labels.__values}", "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": 0 }, { "color": "red", "value": 80 } ] } }, "overrides": [ { "matcher": { "id": "byName", "options": "_value" }, "properties": [ { "id": "displayName", "value": "Count" } ] } ] }, "gridPos": { "h": 9, "w": 24, "x": 0, "y": 103 }, "id": 39, "options": { "cellHeight": "sm", "frameIndex": 1, "showHeader": true, "sortBy": [ { "desc": true, "displayName": "Count" } ] }, "pluginVersion": "12.3.1", "targets": [ { "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "query": "from(bucket: v.defaultBucket)\r\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\r\n |> filter(fn: (r) => r[\"_measurement\"] == \"Redirections\" or r[\"_measurement\"] == \"ReverseProxyConnections\")\r\n |> filter(fn: (r) => r[\"Domain\"] =~ /^${domainquery:regex}$/)\r\n |> filter(fn: (r) => r[\"_field\"] == \"Asn\") \r\n |> group(columns: [\"Asn\"])\r\n |> count()\r\n |> drop(columns: [\"_start\", \"_stop\"])\r\n |> yield(name: \"alias\")\r\n \r\n ", "refId": "A" } ], "title": "ASN (per IP)", "transformations": [ { "id": "labelsToFields", "options": {} }, { "id": "merge", "options": {} } ], "type": "table" } ], "preload": false, "refresh": "30s", "schemaVersion": 42, "tags": [], "templating": { "list": [ { "current": {}, "datasource": { "type": "influxdb", "uid": "${DS_INFLUXDB-NPMGRAFSTATS}" }, "definition": "import \"influxdata/influxdb/schema\"\r\nschema.tagValues(\r\n bucket: v.defaultBucket,\r\n tag: \"Domain\"\r\n)", "includeAll": true, "label": "Domain", "multi": true, "name": "domainquery", "options": [], "query": "import \"influxdata/influxdb/schema\"\r\nschema.tagValues(\r\n bucket: v.defaultBucket,\r\n tag: \"Domain\"\r\n)", "refresh": 2, "regex": "", "sort": 1, "type": "query" } ] }, "time": { "from": "now-6h", "to": "now" }, "timepicker": { "refresh_intervals": [ "5s", "10s", "15s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d" ] }, "timezone": "", "title": "npmGrafStats Map Dashboard v3.1+ InfluxDBv2 WITH filter", "uid": "pvWDTV_MW", "version": 5, "weekStart": "", "id": null } ================================================ FILE: src/abuse_checker.py ================================================ """AbuseIPDB checker with SQLite WAL-mode cache (thread-safe).""" import json import logging import os import sqlite3 import threading import time import requests from config import ABUSEIP_CACHE_DB, ABUSEIP_CACHE_JSON, CACHE_TTL_HOURS, DATA_DIR logger = logging.getLogger(__name__) _CREATE_TABLE = """ CREATE TABLE IF NOT EXISTS abuse_cache ( ip TEXT PRIMARY KEY, confidence_score INTEGER, total_reports INTEGER, data_json TEXT, fetched_at REAL ) """ class AbuseChecker: def __init__(self, api_key: str | None): self._api_key = api_key self._conn: sqlite3.Connection | None = None self._lock = threading.Lock() if not api_key: logger.info("AbuseIPDB disabled (no API key)") return self._init_db() def _init_db(self): os.makedirs(DATA_DIR, exist_ok=True) self._conn = sqlite3.connect(ABUSEIP_CACHE_DB, check_same_thread=False) self._conn.execute("PRAGMA journal_mode=WAL") self._conn.execute(_CREATE_TABLE) self._conn.commit() self._migrate_json_cache() self._cleanup_expired() def _migrate_json_cache(self): """Migrate existing JSON cache to SQLite on first run.""" if not os.path.isfile(ABUSEIP_CACHE_JSON): return try: with open(ABUSEIP_CACHE_JSON, "r") as f: data = json.load(f) count = 0 for ip, entry in data.items(): ts = entry.get("timestamp", 0) d = entry.get("data", {}) self._conn.execute( "INSERT OR IGNORE INTO abuse_cache (ip, confidence_score, total_reports, data_json, fetched_at) VALUES (?, ?, ?, ?, ?)", (ip, d.get("abuseConfidenceScore", 0), d.get("totalReports", 0), json.dumps(d), ts), ) count += 1 self._conn.commit() # Rename old file os.rename(ABUSEIP_CACHE_JSON, ABUSEIP_CACHE_JSON + ".migrated") logger.info("Migrated %d entries from JSON cache to SQLite", count) except Exception as e: logger.warning("JSON cache migration failed: %s", e) def _cleanup_expired(self): cutoff = time.time() - CACHE_TTL_HOURS * 3600 if self._conn: self._conn.execute("DELETE FROM abuse_cache WHERE fetched_at < ?", (cutoff,)) self._conn.commit() logger.info("Cleaned up expired abuse cache entries (older than %dh)", CACHE_TTL_HOURS) @property def enabled(self) -> bool: return self._api_key is not None def check(self, ip: str) -> tuple[int, int]: """Returns (confidence_score, total_reports). (0, 0) if unavailable.""" if not self._api_key or not self._conn: return 0, 0 cutoff = time.time() - CACHE_TTL_HOURS * 3600 with self._lock: row = self._conn.execute( "SELECT confidence_score, total_reports FROM abuse_cache WHERE ip = ? AND fetched_at >= ?", (ip, cutoff), ).fetchone() if row: logger.debug("AbuseIPDB cache HIT for %s", ip) return row[0], row[1] # Cache miss - fetch from API (outside lock to avoid blocking other threads) logger.debug("AbuseIPDB cache MISS for %s", ip) try: resp = requests.get( "https://api.abuseipdb.com/api/v2/check", params={"ipAddress": ip, "maxAgeInDays": "90"}, headers={"Accept": "application/json", "Key": self._api_key}, timeout=10, ) resp.raise_for_status() api_data = resp.json().get("data", {}) cs = api_data.get("abuseConfidenceScore", 0) tr = api_data.get("totalReports", 0) with self._lock: self._conn.execute( "INSERT OR REPLACE INTO abuse_cache (ip, confidence_score, total_reports, data_json, fetched_at) VALUES (?, ?, ?, ?, ?)", (ip, cs, tr, json.dumps(api_data), time.time()), ) self._conn.commit() return cs, tr except Exception as e: logger.warning("AbuseIPDB API error for %s: %s", ip, e) return 0, 0 def close(self): if self._conn: self._conn.close() ================================================ FILE: src/config.py ================================================ """Centralized configuration loaded from environment variables and files.""" import os import logging logger = logging.getLogger(__name__) DATA_DIR = "/data" GEOLITE_DIR = "/geolite" LOGS_DIR = "/logs" CITY_DB_PATH = os.path.join(GEOLITE_DIR, "GeoLite2-City.mmdb") ASN_DB_PATH = os.path.join(GEOLITE_DIR, "GeoLite2-ASN.mmdb") MONITORING_IPS_FILE = os.path.join(DATA_DIR, "monitoringips.txt") INFLUX_TOKEN_FILE = os.path.join(DATA_DIR, "influxdb-token.txt") ABUSEIP_KEY_FILE = os.path.join(DATA_DIR, "abuseipdb-key.txt") ABUSEIP_CACHE_DB = os.path.join(DATA_DIR, "abuseip_cache.db") ABUSEIP_CACHE_JSON = os.path.join(DATA_DIR, "abuseip_cache.json") CACHE_TTL_HOURS = 48 def _read_file_stripped(path: str) -> str | None: try: with open(path, "r") as f: value = f.read().strip() return value if value else None except (OSError, IOError): return None def load_config() -> dict: """Load and validate all configuration. Returns a config dict.""" cfg = {} # InfluxDB cfg["influx_host"] = os.getenv("INFLUX_HOST", "http://influxdb:8086") cfg["influx_bucket"] = os.getenv("INFLUX_BUCKET", "npmgrafstats") cfg["influx_org"] = os.getenv("INFLUX_ORG", "npmgrafstats") cfg["influx_token"] = os.getenv("INFLUX_TOKEN") or _read_file_stripped(INFLUX_TOKEN_FILE) if not cfg["influx_token"]: raise SystemExit("No InfluxDB Token found. Set INFLUX_TOKEN or provide /data/influxdb-token.txt") # Feature flags cfg["redirection_logs"] = os.getenv("REDIRECTION_LOGS", "FALSE").upper() cfg["internal_logs"] = os.getenv("INTERNAL_LOGS", "FALSE").upper() == "TRUE" cfg["monitoring_logs"] = os.getenv("MONITORING_LOGS", "FALSE").upper() == "TRUE" # AbuseIPDB cfg["abuseip_key"] = os.getenv("ABUSEIP_KEY") or _read_file_stripped(ABUSEIP_KEY_FILE) # GeoIP availability cfg["has_city_db"] = os.path.isfile(CITY_DB_PATH) cfg["has_asn_db"] = os.path.isfile(ASN_DB_PATH) # Monitoring IPs file cfg["has_monitoring_file"] = os.path.isfile(MONITORING_IPS_FILE) # External IP (best-effort) cfg["external_ip"] = _get_external_ip() logger.info("Configuration loaded. redirection_logs=%s internal_logs=%s monitoring_logs=%s abuseip=%s asn_db=%s", cfg["redirection_logs"], cfg["internal_logs"], cfg["monitoring_logs"], bool(cfg["abuseip_key"]), cfg["has_asn_db"]) return cfg def _get_external_ip() -> str | None: try: import urllib.request with urllib.request.urlopen("https://ifconfig.me/ip", timeout=10) as resp: return resp.read().decode().strip() except Exception as e: logger.warning("Could not determine external IP: %s", e) return None ================================================ FILE: src/geo_lookup.py ================================================ """Persistent GeoIP City + ASN lookups.""" import logging import geoip2.database import geoip2.errors from config import CITY_DB_PATH, ASN_DB_PATH logger = logging.getLogger(__name__) class GeoResult: __slots__ = ('latitude', 'longitude', 'iso_code', 'country', 'state', 'city', 'zip_code', 'asn') def __init__(self): self.latitude = 0.0 self.longitude = 0.0 self.iso_code = "" self.country = "" self.state = "" self.city = "" self.zip_code = "" self.asn = "" class GeoLookup: def __init__(self, has_city_db: bool, has_asn_db: bool): self._city_reader = None self._asn_reader = None if has_city_db: try: self._city_reader = geoip2.database.Reader(CITY_DB_PATH) logger.info("GeoIP City DB opened") except Exception as e: logger.error("Failed to open City DB: %s", e) if has_asn_db: try: self._asn_reader = geoip2.database.Reader(ASN_DB_PATH) logger.info("GeoIP ASN DB opened") except Exception as e: logger.error("Failed to open ASN DB: %s", e) def lookup(self, ip: str) -> GeoResult: result = GeoResult() if self._city_reader: try: resp = self._city_reader.city(ip) result.latitude = resp.location.latitude or 0.0 result.longitude = resp.location.longitude or 0.0 result.iso_code = resp.country.iso_code or "" result.country = resp.country.name or "" result.state = resp.subdivisions.most_specific.name or "" if resp.subdivisions else "" result.city = resp.city.name or "" result.zip_code = resp.postal.code or "" except geoip2.errors.AddressNotFoundError: logger.debug("City DB: address not found for %s", ip) except Exception as e: logger.warning("City lookup error for %s: %s", ip, e) if self._asn_reader: try: resp = self._asn_reader.asn(ip) result.asn = resp.autonomous_system_organization or "" except geoip2.errors.AddressNotFoundError: result.asn = "No ASN associated" except Exception as e: result.asn = f"ASN error: {e}" return result def close(self): if self._city_reader: self._city_reader.close() if self._asn_reader: self._asn_reader.close() ================================================ FILE: src/influx_writer.py ================================================ """Persistent InfluxDB writer - single writes per log line.""" import logging import influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS logger = logging.getLogger(__name__) _MONTH_MAP = { 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12', } def _convert_timestamp(raw: str) -> str: """Convert '01/Jan/2024:12:00:00 +0000' to ISO format.""" # raw = "DD/Mon/YYYY:HH:MM:SS +ZZZZ" month = _MONTH_MAP.get(raw[3:6], '12') return f"{raw[7:11]}-{month}-{raw[0:2]}T{raw[12:20]}{raw[21:24]}:{raw[24:26]}" class InfluxWriter: def __init__(self, host: str, token: str, org: str, bucket: str): self._org = org self._bucket = bucket self._client = influxdb_client.InfluxDBClient(url=host, token=token, org=org) self._write_api = self._client.write_api(write_options=SYNCHRONOUS) logger.info("InfluxDB client connected to %s", host) def write_external(self, measurement: str, ip: str, domain: str, length: int, target_ip: str, timestamp: str, status_code: int, user_agent_info: tuple, geo, abuse_scores: tuple, abuse_enabled: bool = False): """Write an external/monitoring IP data point.""" browser, browser_version, os_family = user_agent_info confidence_score, total_reports = abuse_scores time_str = _convert_timestamp(timestamp) point = influxdb_client.Point(measurement) # Tags (exactly matching original Getipinfo.py) point.tag("key", geo.iso_code) point.tag("latitude", geo.latitude) point.tag("longitude", geo.longitude) point.tag("Domain", domain) point.tag("City", geo.city) point.tag("State", geo.state) point.tag("Name", geo.country) point.tag("IP", ip) point.tag("Target", target_ip) if geo.asn: point.tag("Asn", geo.asn) if abuse_enabled: point.tag("abuseConfidenceScore", str(confidence_score)) point.tag("totalReports", str(total_reports)) # Fields (exactly matching original) point.field("Domain", domain) point.field("latitude", geo.latitude) point.field("longitude", geo.longitude) point.field("State", geo.state) point.field("City", geo.city) point.field("key", geo.iso_code) point.field("IP", ip) point.field("Target", target_ip) point.field("browser", browser) point.field("browser_version", browser_version) point.field("os", os_family) if geo.asn: point.field("Asn", geo.asn) point.field("Name", geo.country) point.field("length", length) point.field("statuscode", status_code) point.field("metric", 1) if abuse_enabled: point.field("abuseConfidenceScore", str(confidence_score)) point.field("totalReports", str(total_reports)) point.time(time_str) self._write_api.write(bucket=self._bucket, org=self._org, record=point) def write_internal(self, measurement: str, ip: str, domain: str, length: int, target_ip: str, timestamp: str, status_code: int, user_agent_info: tuple): """Write an internal IP data point (no geo, no abuse).""" browser, browser_version, os_family = user_agent_info time_str = _convert_timestamp(timestamp) point = influxdb_client.Point(measurement) # Tags (exactly matching original Internalipinfo.py) point.tag("Domain", domain) point.tag("IP", ip) point.tag("Target", target_ip) # Fields point.field("Domain", domain) point.field("IP", ip) point.field("Target", target_ip) point.field("browser", browser) point.field("browser_version", browser_version) point.field("os", os_family) point.field("length", length) point.field("statuscode", status_code) point.field("metric", 1) point.time(time_str) self._write_api.write(bucket=self._bucket, org=self._org, record=point) def close(self): self._client.close() logger.info("InfluxDB client closed") ================================================ FILE: src/ip_classifier.py ================================================ """Classify IPs as internal, external-own, monitoring, or external.""" import ipaddress import logging import os from config import MONITORING_IPS_FILE logger = logging.getLogger(__name__) def _parse_networks(filepath: str) -> list[ipaddress.IPv4Network | ipaddress.IPv6Network]: """Load CIDR networks and single IPs from monitoringips.txt.""" networks = [] if not os.path.isfile(filepath): return networks with open(filepath, "r") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue try: networks.append(ipaddress.ip_network(line, strict=False)) except ValueError: logger.warning("Invalid network in monitoring IPs file: %s", line) logger.info("Loaded %d monitoring networks/IPs", len(networks)) return networks # Private networks for internal IP detection _PRIVATE_NETS = [ ipaddress.ip_network("10.0.0.0/8"), ipaddress.ip_network("172.16.0.0/12"), ipaddress.ip_network("192.168.0.0/16"), ipaddress.ip_network("::1/128"), ipaddress.ip_network("fc00::/7"), ipaddress.ip_network("fe80::/10"), ] class IPClassifier: def __init__(self, external_ip: str | None, has_monitoring_file: bool): self._external_ip = external_ip self._monitoring_nets = _parse_networks(MONITORING_IPS_FILE) if has_monitoring_file else [] def classify(self, ip_str: str) -> str: """Returns 'internal', 'monitoring', or 'external'.""" try: addr = ipaddress.ip_address(ip_str) except ValueError: return "external" # Check internal if any(addr in net for net in _PRIVATE_NETS): return "internal" if self._external_ip and ip_str == self._external_ip: return "internal" # Check monitoring if self._monitoring_nets: if any(addr in net for net in self._monitoring_nets): return "monitoring" return "external" ================================================ FILE: src/log_parser.py ================================================ """Compiled regex parsers for NPM proxy-host and redirection log formats. NPM generates two types of access logs with DIFFERENT formats: Proxy-host (has [Sent-to]): [DD/Mon/YYYY:HH:MM:SS +0000] - STATUS STATUS - METHOD SCHEME DOMAIN "PATH" [Client IP] [Length N] [Gzip -] [Sent-to IP] "UA" "REFERER" Redirection (NO [Sent-to], only one status code): [DD/Mon/YYYY:HH:MM:SS +0000] STATUS - METHOD SCHEME DOMAIN "PATH" [Client IP] [Length N] [Gzip -] "UA" "REFERER" Key differences: - Proxy has "- STATUS STATUS -" after timestamp, redirect has "STATUS -" - Proxy has [Sent-to IP] before the UA, redirect does not - Field indices shift by 2 between formats (proxy domain=index 8, redirect domain=index 6) """ import re import logging logger = logging.getLogger(__name__) # --- IP patterns (non-capturing, used inside capturing groups in the regexes) --- _IPV4 = r'(?:(?:\d{1,3}\.){3}\d{1,3})' _IPV6 = ( r'(?:' r'(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|' r'(?:[0-9a-fA-F]{1,4}:){1,7}:|' r'(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|' r'(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|' r'(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|' r'(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|' r'(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|' r'[0-9a-fA-F]{1,4}:(?::[0-9a-fA-F]{1,4}){1,6}|' r':(?::[0-9a-fA-F]{1,4}){1,7}|' r'::1' r')' ) # Combined pattern matching both IPv4 and IPv6 _IP = rf'(?:{_IPV4}|{_IPV6})' # --- Proxy-host log regex --- # Example: [12/Mar/2026:00:44:15 +0000] - 500 500 - POST http hausi.example.com "/" [Client 1.2.3.4] [Length 63] [Gzip -] [Sent-to 10.0.0.1] "Mozilla/5.0 ..." "-" # # Capture groups: # 1: timestamp (DD/Mon/YYYY:HH:MM:SS +0000) # 2: status_code (first of the two status codes) # 3: domain (unquoted hostname) # 4: client_ip (from [Client ...]) # 5: length (from [Length ...]) # 6: target_ip (from [Sent-to ...]) # 7: user_agent (first quoted string after [Sent-to]) _PROXY_RE = re.compile( r'^\[(\d{2}/\w{3}/\d{4}:\d{2}:\d{2}:\d{2} [+\-]\d{4})\]' # [timestamp] r'\s+-\s+' # " - " separator r'(\d{3})' # status code (first) r'\s+\d{3}\s+-\s+\w+\s+\w+\s+' # second status, " - ", METHOD, SCHEME r'(\S+)' # domain (unquoted) r'\s+"[^"]*"' # "path" r'\s+\[Client\s+(' + _IP + r')\]' # [Client IP] r'\s+\[Length\s+(\d+)\]' # [Length N] r'\s+\[Gzip\s+[^\]]*\]' # [Gzip ...] r'\s+\[Sent-to\s+(' + _IP + r')\]' # [Sent-to IP] r'\s+"([^"]*)"' # "user-agent" ) # --- Redirection log regex --- # Example: [08/Mar/2026:15:10:15 +0000] 301 - GET http www.cycling-basti.de "/" [Client 43.130.67.6] [Length 166] [Gzip -] "Mozilla/5.0 ..." "-" # # Capture groups: # 1: timestamp # 2: status_code (only one, unlike proxy) # 3: domain # 4: client_ip # 5: user_agent # # Key difference to proxy: no [Sent-to], so after [Gzip] comes "UA" directly. _REDIRECT_RE = re.compile( r'^\[(\d{2}/\w{3}/\d{4}:\d{2}:\d{2}:\d{2} [+\-]\d{4})\]' # [timestamp] r'\s+' r'(\d{3})' # status code r'\s+-\s+\w+\s+\w+\s+' # " - ", METHOD, SCHEME r'(\S+)' # domain (unquoted) r'\s+"[^"]*"' # "path" r'\s+\[Client\s+(' + _IP + r')\]' # [Client IP] r'\s+\[Length\s+\d+\]' # [Length N] (value not captured) r'\s+\[Gzip\s+[^\]]*\]' # [Gzip ...] r'\s+"([^"]*)"' # "user-agent" (directly after Gzip, no Sent-to) ) # --- Data classes --- class ProxyLogEntry: __slots__ = ('timestamp', 'status_code', 'outside_ip', 'domain', 'length', 'target_ip', 'user_agent') def __init__(self, timestamp, status_code, outside_ip, domain, length, target_ip, user_agent): self.timestamp = timestamp self.status_code = status_code self.outside_ip = outside_ip self.domain = domain self.length = length self.target_ip = target_ip self.user_agent = user_agent class RedirectLogEntry: __slots__ = ('timestamp', 'status_code', 'outside_ip', 'domain', 'user_agent') def __init__(self, timestamp, status_code, outside_ip, domain, user_agent): self.timestamp = timestamp self.status_code = status_code self.outside_ip = outside_ip self.domain = domain self.user_agent = user_agent # --- Parsers --- def parse_proxy_line(line: str) -> ProxyLogEntry | None: """Parse a proxy-host access log line. Falls back to field-based extraction.""" m = _PROXY_RE.match(line) if m: return ProxyLogEntry( timestamp=m.group(1), status_code=int(m.group(2)), outside_ip=m.group(4), domain=m.group(3), length=int(m.group(5)), target_ip=m.group(6), user_agent=m.group(7), ) return _fallback_proxy_parse(line) def parse_redirect_line(line: str) -> RedirectLogEntry | None: """Parse a redirection-host access log line. Falls back to field-based extraction.""" m = _REDIRECT_RE.match(line) if m: return RedirectLogEntry( timestamp=m.group(1), status_code=int(m.group(2)), outside_ip=m.group(4), domain=m.group(3), user_agent=m.group(5), ) return _fallback_redirect_parse(line) # --- Fallback parsers (for edge cases the regex doesn't cover) --- def _fallback_proxy_parse(line: str) -> ProxyLogEntry | None: """Field-based proxy parser. Extracts known fields by pattern/position.""" if len(line) < 28 or line[0] != '[': return None timestamp = line[1:27] client_match = re.search(r'\[Client\s+(' + _IP + r')\]', line) if not client_match: return None outside_ip = client_match.group(1) sentto_match = re.search(r'\[Sent-to\s+(' + _IP + r')\]', line) target_ip = sentto_match.group(1) if sentto_match else outside_ip parts = line.split() # Proxy format field indices (space-split): # 0:[TS 1:+0000] 2:- 3:STATUS 4:STATUS 5:- 6:METHOD 7:SCHEME 8:DOMAIN ... domain = parts[8] if len(parts) > 8 else "unknown" try: status_code = int(parts[3]) if len(parts) > 3 else 0 except ValueError: status_code = 0 # Find [Length N] anywhere in the line length = 0 for i, p in enumerate(parts): if p == '[Length' and i + 1 < len(parts): try: length = int(parts[i + 1].rstrip(']')) except ValueError: pass break # UA is the first quoted string after [Sent-to] or [Gzip] ua_match = re.search(r'\[Sent-to [^\]]+\]\s*"([^"]*)"', line) if not ua_match: ua_match = re.search(r'\[Gzip\s+[^\]]*\]\s*"([^"]*)"', line) user_agent = ua_match.group(1) if ua_match else "" return ProxyLogEntry(timestamp, status_code, outside_ip, domain, length, target_ip, user_agent) def _fallback_redirect_parse(line: str) -> RedirectLogEntry | None: """Field-based redirect parser. No [Sent-to] field in redirects.""" if len(line) < 28 or line[0] != '[': return None timestamp = line[1:27] client_match = re.search(r'\[Client\s+(' + _IP + r')\]', line) if not client_match: return None outside_ip = client_match.group(1) parts = line.split() # Redirect format field indices (space-split): # 0:[TS 1:+0000] 2:STATUS 3:- 4:METHOD 5:SCHEME 6:DOMAIN ... domain = parts[6] if len(parts) > 6 else "unknown" try: status_code = int(parts[2]) if len(parts) > 2 else 0 except ValueError: status_code = 0 # UA is the first quoted string after [Gzip] (no [Sent-to] in redirects) ua_match = re.search(r'\[Gzip\s+[^\]]*\]\s*"([^"]*)"', line) user_agent = ua_match.group(1) if ua_match else "" return RedirectLogEntry(timestamp, status_code, outside_ip, domain, user_agent) ================================================ FILE: src/log_watcher.py ================================================ """Tail -F equivalent: watch log files for new lines, handle rotation.""" import logging import os import time import threading logger = logging.getLogger(__name__) class LogWatcher: """Watches a single log file, calling callback for each new line. Handles log rotation (file deleted/recreated).""" def __init__(self, filepath: str, callback, stop_event: threading.Event): self._filepath = filepath self._callback = callback self._stop = stop_event def run(self): logger.info("Watching: %s", self._filepath) while not self._stop.is_set(): try: self._tail() except Exception as e: logger.error("Error watching %s: %s", self._filepath, e) if self._stop.wait(2): break def _tail(self): # Wait for file to exist while not os.path.isfile(self._filepath): if self._stop.wait(1): return with open(self._filepath, "r") as f: # Seek to end f.seek(0, 2) inode = os.fstat(f.fileno()).st_ino while not self._stop.is_set(): line = f.readline() if line: line = line.rstrip("\n") if line: try: self._callback(line) except Exception as e: logger.error("Callback error for %s: %s", self._filepath, e) else: # No new data - check for rotation try: if not os.path.isfile(self._filepath): logger.info("File removed, waiting for recreation: %s", self._filepath) return # Will re-enter _tail new_inode = os.stat(self._filepath).st_ino if new_inode != inode: logger.info("File rotated: %s", self._filepath) return # Will re-enter _tail except OSError: return # File gone, retry self._stop.wait(0.1) ================================================ FILE: src/main.py ================================================ #!/usr/bin/env python3 """npmGrafStats - Python rewrite. Single entrypoint.""" import glob import logging import os import signal import sys import threading from config import load_config, LOGS_DIR from log_watcher import LogWatcher from log_parser import parse_proxy_line, parse_redirect_line from geo_lookup import GeoLookup from abuse_checker import AbuseChecker from ua_parser_util import parse_user_agent from influx_writer import InfluxWriter from ip_classifier import IPClassifier VERSION = "4.0.0" _log_level = os.getenv("LOG_LEVEL", "INFO").upper() logging.basicConfig( level=getattr(logging, _log_level, logging.INFO), format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", stream=sys.stdout, ) logger = logging.getLogger("npmGrafStats") # When VERBOSE_LOGGING=TRUE, log every processed request at INFO level (like the original shell scripts) VERBOSE = os.getenv("VERBOSE_LOGGING", "FALSE").upper() == "TRUE" # Global stop event stop_event = threading.Event() def main(): logger.info("npmGrafStats v%s starting (log_level=%s, verbose=%s)", VERSION, _log_level, VERBOSE) cfg = load_config() # Initialize shared services geo = GeoLookup(cfg["has_city_db"], cfg["has_asn_db"]) abuse = AbuseChecker(cfg["abuseip_key"]) influx = InfluxWriter(cfg["influx_host"], cfg["influx_token"], cfg["influx_org"], cfg["influx_bucket"]) classifier = IPClassifier(cfg["external_ip"], cfg["has_monitoring_file"]) # Counters for periodic stats _stats = {"processed": 0, "errors": 0, "written": 0} _stats_lock = threading.Lock() def handle_proxy_line(line: str): entry = parse_proxy_line(line) if not entry: logger.debug("Failed to parse proxy line: %.200s", line) return ip_type = classifier.classify(entry.outside_ip) ua_info = parse_user_agent(entry.user_agent) if VERBOSE: logger.info("[PROXY] %s %s -> %s (status=%d, len=%d, type=%s)", entry.outside_ip, entry.domain, entry.target_ip, entry.status_code, entry.length, ip_type) try: if ip_type == "internal": logger.debug("Internal IP: %s -> %s", entry.outside_ip, entry.domain) if cfg["internal_logs"]: influx.write_internal( "InternalRProxyIPs", entry.outside_ip, entry.domain, entry.length, entry.target_ip, entry.timestamp, entry.status_code, ua_info, ) elif ip_type == "monitoring": logger.debug("Monitoring IP: %s -> %s", entry.outside_ip, entry.domain) if cfg["monitoring_logs"]: geo_result = geo.lookup(entry.outside_ip) abuse_scores = abuse.check(entry.outside_ip) influx.write_external( "MonitoringRProxyIPs", entry.outside_ip, entry.domain, entry.length, entry.target_ip, entry.timestamp, entry.status_code, ua_info, geo_result, abuse_scores, abuse_enabled=abuse.enabled, ) else: geo_result = geo.lookup(entry.outside_ip) abuse_scores = abuse.check(entry.outside_ip) influx.write_external( "ReverseProxyConnections", entry.outside_ip, entry.domain, entry.length, entry.target_ip, entry.timestamp, entry.status_code, ua_info, geo_result, abuse_scores, abuse_enabled=abuse.enabled, ) with _stats_lock: _stats["written"] += 1 except Exception as e: logger.error("InfluxDB write FAILED for %s %s -> %s: %s", entry.outside_ip, entry.domain, entry.target_ip, e) with _stats_lock: _stats["errors"] += 1 with _stats_lock: _stats["processed"] += 1 def handle_redirect_line(line: str): entry = parse_redirect_line(line) if not entry: logger.debug("Failed to parse redirect line: %.200s", line) return ip_type = classifier.classify(entry.outside_ip) ua_info = parse_user_agent(entry.user_agent) if VERBOSE: logger.info("[REDIRECT] %s %s (status=%d, type=%s)", entry.outside_ip, entry.domain, entry.status_code, ip_type) try: if ip_type == "internal": logger.debug("Internal IP (redirect): %s -> %s", entry.outside_ip, entry.domain) if cfg["internal_logs"]: influx.write_internal( "InternalRProxyIPs", entry.outside_ip, entry.domain, 0, "redirect", entry.timestamp, entry.status_code, ua_info, ) elif ip_type == "monitoring": logger.debug("Monitoring IP (redirect): %s -> %s", entry.outside_ip, entry.domain) if cfg["monitoring_logs"]: geo_result = geo.lookup(entry.outside_ip) abuse_scores = abuse.check(entry.outside_ip) influx.write_external( "MonitoringRProxyIPs", entry.outside_ip, entry.domain, 0, "redirect", entry.timestamp, entry.status_code, ua_info, geo_result, abuse_scores, abuse_enabled=abuse.enabled, ) else: geo_result = geo.lookup(entry.outside_ip) abuse_scores = abuse.check(entry.outside_ip) influx.write_external( "Redirections", entry.outside_ip, entry.domain, 0, "redirect", entry.timestamp, entry.status_code, ua_info, geo_result, abuse_scores, abuse_enabled=abuse.enabled, ) with _stats_lock: _stats["written"] += 1 except Exception as e: logger.error("InfluxDB write FAILED for redirect %s %s: %s", entry.outside_ip, entry.domain, e) with _stats_lock: _stats["errors"] += 1 with _stats_lock: _stats["processed"] += 1 # Collect log files and start watcher threads threads: list[threading.Thread] = [] redirection_mode = cfg["redirection_logs"] # TRUE, FALSE, or ONLY if redirection_mode != "ONLY": proxy_logs = sorted(glob.glob(os.path.join(LOGS_DIR, "proxy-host-*_access.log"))) logger.info("Found %d proxy-host log files", len(proxy_logs)) for logfile in proxy_logs: watcher = LogWatcher(logfile, handle_proxy_line, stop_event) t = threading.Thread(target=watcher.run, name=f"proxy:{os.path.basename(logfile)}", daemon=True) t.start() threads.append(t) if redirection_mode in ("TRUE", "ONLY"): redirect_logs = sorted(glob.glob(os.path.join(LOGS_DIR, "redirection-host-*_access.log"))) logger.info("Found %d redirection-host log files", len(redirect_logs)) for logfile in redirect_logs: watcher = LogWatcher(logfile, handle_redirect_line, stop_event) t = threading.Thread(target=watcher.run, name=f"redirect:{os.path.basename(logfile)}", daemon=True) t.start() threads.append(t) if not threads: logger.warning("No log files found to watch!") logger.info("Started %d watcher threads", len(threads)) # Graceful shutdown def shutdown(signum, frame): logger.info("Received signal %d, shutting down...", signum) stop_event.set() signal.signal(signal.SIGTERM, shutdown) signal.signal(signal.SIGINT, shutdown) # Wait for stop try: stop_event.wait() except KeyboardInterrupt: stop_event.set() # Cleanup logger.info("Stats: processed=%d written=%d errors=%d", _stats["processed"], _stats["written"], _stats["errors"]) logger.info("Waiting for threads to finish...") for t in threads: t.join(timeout=5) abuse.close() influx.close() geo.close() logger.info("npmGrafStats shutdown complete") if __name__ == "__main__": main() ================================================ FILE: src/requirements.txt ================================================ geoip2 influxdb-client ua-parser requests ================================================ FILE: src/ua_parser_util.py ================================================ """User-Agent parsing utility.""" from ua_parser import user_agent_parser def parse_user_agent(ua_string: str) -> tuple[str, str, str]: """Returns (browser, browser_version, os_family).""" parsed = user_agent_parser.Parse(ua_string) browser = parsed['user_agent']['family'] or 'Unknown' major = parsed['user_agent']['major'] or '0' browser_version = f"{browser}: {major}" if parsed['user_agent']['minor']: browser_version += f".{parsed['user_agent']['minor']}" os_family = parsed['os']['family'] or 'Unknown' return browser, browser_version, os_family