[
  {
    "path": ".gitignore",
    "content": "openvpn_exporter\n.idea\ndist\n"
  },
  {
    "path": ".goreleaser.yml",
    "content": "# This is an example goreleaser.yaml file with some sane defaults.\n# Make sure to check the documentation at http://goreleaser.com\nbefore:\n  hooks:\n  - go mod download\nbuilds:\n- env:\n  - CGO_ENABLED=0\n  goarch:\n  - amd64\n  goos:\n  - linux\n  - darwin\ndockers:\n- image_templates:\n  - \"kumina/openvpn-exporter:latest\"\n  - \"kumina/openvpn-exporter:{{ .Tag }}\"\n  build_flag_templates:\n  - \"--label=org.label-schema.schema-version=1.0\"\n  - \"--label=org.label-schema.version={{ .Version }}\"\n  - \"--label=org.label-schema.name={{ .ProjectName }}\"\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "## 0.2.1 / 2018-04-06\n\n* [BUGFIX] CLIENT_LIST metrics collect fixed.\n\n## 0.2 / 2017-04-14\n\n* [FEATURE] Replace client and route counters by per-entry metrics.\n\n## 0.1 / 2017-04-03\n\n* [ENHANCEMENT] Initial release\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM scratch\nCOPY openvpn_exporter /bin/openvpn_exporter\nENTRYPOINT [\"/bin/openvpn_exporter\"]\nCMD [ \"-h\" ]\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Prometheus OpenVPN exporter\n\n**Please note:** This repository is currently unmaintained. Due to insufficient time and not using the exporter anymore\nwe decided to archive this project.\n\n---\n\nThis repository provides code for a simple Prometheus metrics exporter\nfor [OpenVPN](https://openvpn.net/). Right now it can parse files\ngenerated by OpenVPN's `--status`, having one of the following formats:\n\n* Client statistics,\n* Server statistics with `--status-version 2` (comma delimited),\n* Server statistics with `--status-version 3` (tab delimited).\n\nAs it is not uncommon to run multiple instances of OpenVPN on a single\nsystem (e.g., multiple servers, multiple clients or a mixture of both),\nthis exporter can be configured to scrape and export the status of\nmultiple status files, using the `-openvpn.status_paths` command line\nflag. Paths need to be comma separated. Metrics for all status files are\nexported over TCP port 9176.\n\nPlease refer to this utility's `main()` function for a full list of\nsupported command line flags.\n\n## Exposed metrics example\n\n### Client statistics\n\nFor clients status files, the exporter generates metrics that may look\nlike this:\n\n```\nopenvpn_client_auth_read_bytes_total{status_path=\"...\"} 3.08854782e+08\nopenvpn_client_post_compress_bytes_total{status_path=\"...\"} 4.5446864e+07\nopenvpn_client_post_decompress_bytes_total{status_path=\"...\"} 2.16965355e+08\nopenvpn_client_pre_compress_bytes_total{status_path=\"...\"} 4.538819e+07\nopenvpn_client_pre_decompress_bytes_total{status_path=\"...\"} 1.62596168e+08\nopenvpn_client_tcp_udp_read_bytes_total{status_path=\"...\"} 2.92806201e+08\nopenvpn_client_tcp_udp_write_bytes_total{status_path=\"...\"} 1.97558969e+08\nopenvpn_client_tun_tap_read_bytes_total{status_path=\"...\"} 1.53789941e+08\nopenvpn_client_tun_tap_write_bytes_total{status_path=\"...\"} 3.08764078e+08\nopenvpn_status_update_time_seconds{status_path=\"...\"} 1.490092749e+09\nopenvpn_up{status_path=\"...\"} 1\n```\n\n### Server statistics\n\nFor server status files (both version 2 and 3), the exporter generates\nmetrics that may look like this:\n\n```\nopenvpn_server_client_received_bytes_total{common_name=\"...\",connection_time=\"...\",real_address=\"...\",status_path=\"...\",username=\"...\",virtual_address=\"...\"} 139583\nopenvpn_server_client_sent_bytes_total{common_name=\"...\",connection_time=\"...\",real_address=\"...\",status_path=\"...\",username=\"...\",virtual_address=\"...\"} 710764\nopenvpn_server_route_last_reference_time_seconds{common_name=\"...\",real_address=\"...\",status_path=\"...\",virtual_address=\"...\"} 1.493018841e+09\nopenvpn_status_update_time_seconds{status_path=\"...\"} 1.490089154e+09\nopenvpn_up{status_path=\"...\"} 1\nopenvpn_server_connected_clients 1\n```\n\n## Usage\n\nUsage of openvpn_exporter:\n\n```sh\n  -openvpn.status_paths string\n    \tPaths at which OpenVPN places its status files. (default \"examples/client.status,examples/server2.status,examples/server3.status\")\n  -web.listen-address string\n    \tAddress to listen on for web interface and telemetry. (default \":9176\")\n  -web.telemetry-path string\n    \tPath under which to expose metrics. (default \"/metrics\")\n  -ignore.individuals bool\n        If ignoring metrics for individuals (default false)\n```\n\nE.g:\n\n```sh\nopenvpn_exporter -openvpn.status_paths /etc/openvpn/openvpn-status.log\n```\n\n## Docker\n\nTo use with docker you must mount your status file to `/etc/openvpn_exporter/server.status`.\n\n```sh\ndocker run -p 9176:9176 \\\n  -v /path/to/openvpn_server.status:/etc/openvpn_exporter/server.status \\\n  kumina/openvpn-exporter -openvpn.status_paths /etc/openvpn_exporter/server.status\n```\n\nMetrics should be available at http://localhost:9176/metrics.\n\n## Get a standalone executable binary\n\nYou can download the pre-compiled binaries from the\n[releases page](https://github.com/kumina/openvpn_exporter/releases).\n"
  },
  {
    "path": "examples/client.status",
    "content": "OpenVPN STATISTICS\nUpdated,Tue Mar 21 10:39:09 2017\nTUN/TAP read bytes,153789941\nTUN/TAP write bytes,308764078\nTCP/UDP read bytes,292806201\nTCP/UDP write bytes,197558969\nAuth read bytes,308854782\npre-compress bytes,45388190\npost-compress bytes,45446864\npre-decompress bytes,162596168\npost-decompress bytes,216965355\nEND\n"
  },
  {
    "path": "examples/server2.status",
    "content": "TITLE,OpenVPN 2.3.2 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Dec  2 2014\nTIME,Tue Mar 21 10:39:14 2017,1490089154\nHEADER,CLIENT_LIST,Common Name,Real Address,Virtual Address,Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),Username\nCLIENT_LIST,redacted1,0.0.0.0:19021,0.0.0.0,693438277,228390856,Thu Mar 16 17:09:03 2017,1489680543,UNDEF\nCLIENT_LIST,redacted2,0.0.0.0:60536,0.0.0.0,2925752,3145665,Thu Mar 16 17:08:57 2017,1489680537,UNDEF\nCLIENT_LIST,redacted3,0.0.0.0:28331,0.0.0.0,57316467,611736741,Thu Mar 16 17:08:57 2017,1489680537,UNDEF\nCLIENT_LIST,redacted4,0.0.0.0:52335,0.0.0.0,24289622392,70914674697,Fri Mar 17 11:16:29 2017,1489745789,UNDEF\nCLIENT_LIST,redacted5,0.0.0.0:51865,0.0.0.0,277017840,1544465106,Thu Mar 16 17:09:01 2017,1489680541,UNDEF\nCLIENT_LIST,redacted1,0.0.0.0:19021,0.0.0.0,693438277,228390856,Thu Mar 16 17:09:03 2017,1489680543,UNDEF\nHEADER,ROUTING_TABLE,Virtual Address,Common Name,Real Address,Last Ref,Last Ref (time_t)\nROUTING_TABLE,0.0.0.0,redacted1,0.0.0.0:19021,Tue Mar 21 10:26:48 2017,1490088408\nROUTING_TABLE,0.0.0.0,redacted5,0.0.0.0:51865,Tue Mar 21 10:38:26 2017,1490089106\nROUTING_TABLE,0.0.0.0,redacted3,0.0.0.0:28331,Tue Mar 21 10:39:06 2017,1490089146\nROUTING_TABLE,0.0.0.0,redacted4,0.0.0.0:52335,Tue Mar 21 10:39:13 2017,1490089153\nROUTING_TABLE,0.0.0.0,redacted2,0.0.0.0:60536,Thu Mar 16 17:08:58 2017,1489680538\nROUTING_TABLE,0.0.0.0,redacted1,0.0.0.0:19021,Tue Mar 21 10:26:48 2017,1490088408\nGLOBAL_STATS,Max bcast/mcast queue length,0\nEND\n"
  },
  {
    "path": "examples/server3.status",
    "content": "TITLE\tOpenVPN 2.3.2 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Dec  2 2014\nTIME\tTue Mar 21 10:39:14 2017\t1490089154\nHEADER\tCLIENT_LIST\tCommon Name\tReal Address\tVirtual Address\tBytes Received\tBytes Sent\tConnected Since\tConnected Since (time_t)\tUsername\nCLIENT_LIST\tredacted1\t0.0.0.0:19021\t0.0.0.0\t693438277\t228390856\tThu Mar 16 17:09:03 2017\t1489680543\tUNDEF\nCLIENT_LIST\tredacted2\t0.0.0.0:60536\t0.0.0.0\t2925752\t3145665\tThu Mar 16 17:08:57 2017\t1489680537\tUNDEF\nCLIENT_LIST\tredacted3\t0.0.0.0:28331\t0.0.0.0\t57316467\t611736741\tThu Mar 16 17:08:57 2017\t1489680537\tUNDEF\nCLIENT_LIST\tredacted4\t0.0.0.0:52335\t0.0.0.0\t24289622392\t70914674697\tFri Mar 17 11:16:29 2017\t1489745789\tUNDEF\nCLIENT_LIST\tredacted5\t0.0.0.0:51865\t0.0.0.0\t277017840\t1544465106\tThu Mar 16 17:09:01 2017\t1489680541\tUNDEF\nHEADER\tROUTING_TABLE\tVirtual Address\tCommon Name\tReal Address\tLast Ref\tLast Ref (time_t)\nROUTING_TABLE\t0.0.0.0\tredacted1\t0.0.0.0:19021\tTue Mar 21 10:26:48 2017\t1490088408\nROUTING_TABLE\t0.0.0.0\tredacted5\t0.0.0.0:51865\tTue Mar 21 10:38:26 2017\t1490089106\nROUTING_TABLE\t0.0.0.0\tredacted3\t0.0.0.0:28331\tTue Mar 21 10:39:06 2017\t1490089146\nROUTING_TABLE\t0.0.0.0\tredacted4\t0.0.0.0:52335\tTue Mar 21 10:39:13 2017\t1490089153\nROUTING_TABLE\t0.0.0.0\tredacted2\t0.0.0.0:60536\tThu Mar 16 17:08:58 2017\t1489680538\nGLOBAL_STATS\tMax bcast/mcast queue length\t0\nEND\n"
  },
  {
    "path": "exporters/openvpn_exporter.go",
    "content": "package exporters\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype OpenvpnServerHeader struct {\n\tLabelColumns []string\n\tMetrics      []OpenvpnServerHeaderField\n}\n\ntype OpenvpnServerHeaderField struct {\n\tColumn    string\n\tDesc      *prometheus.Desc\n\tValueType prometheus.ValueType\n}\n\ntype OpenVPNExporter struct {\n\tstatusPaths                 []string\n\topenvpnUpDesc               *prometheus.Desc\n\topenvpnStatusUpdateTimeDesc *prometheus.Desc\n\topenvpnConnectedClientsDesc *prometheus.Desc\n\topenvpnClientDescs          map[string]*prometheus.Desc\n\topenvpnServerHeaders        map[string]OpenvpnServerHeader\n}\n\nfunc NewOpenVPNExporter(statusPaths []string, ignoreIndividuals bool) (*OpenVPNExporter, error) {\n\t// Metrics exported both for client and server statistics.\n\topenvpnUpDesc := prometheus.NewDesc(\n\t\tprometheus.BuildFQName(\"openvpn\", \"\", \"up\"),\n\t\t\"Whether scraping OpenVPN's metrics was successful.\",\n\t\t[]string{\"status_path\"}, nil)\n\topenvpnStatusUpdateTimeDesc := prometheus.NewDesc(\n\t\tprometheus.BuildFQName(\"openvpn\", \"\", \"status_update_time_seconds\"),\n\t\t\"UNIX timestamp at which the OpenVPN statistics were updated.\",\n\t\t[]string{\"status_path\"}, nil)\n\n\t// Metrics specific to OpenVPN servers.\n\topenvpnConnectedClientsDesc := prometheus.NewDesc(\n\t\tprometheus.BuildFQName(\"openvpn\", \"\", \"server_connected_clients\"),\n\t\t\"Number Of Connected Clients\",\n\t\t[]string{\"status_path\"}, nil)\n\n\t// Metrics specific to OpenVPN clients.\n\topenvpnClientDescs := map[string]*prometheus.Desc{\n\t\t\"TUN/TAP read bytes\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(\"openvpn\", \"client\", \"tun_tap_read_bytes_total\"),\n\t\t\t\"Total amount of TUN/TAP traffic read, in bytes.\",\n\t\t\t[]string{\"status_path\"}, nil),\n\t\t\"TUN/TAP write bytes\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(\"openvpn\", \"client\", \"tun_tap_write_bytes_total\"),\n\t\t\t\"Total amount of TUN/TAP traffic written, in bytes.\",\n\t\t\t[]string{\"status_path\"}, nil),\n\t\t\"TCP/UDP read bytes\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(\"openvpn\", \"client\", \"tcp_udp_read_bytes_total\"),\n\t\t\t\"Total amount of TCP/UDP traffic read, in bytes.\",\n\t\t\t[]string{\"status_path\"}, nil),\n\t\t\"TCP/UDP write bytes\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(\"openvpn\", \"client\", \"tcp_udp_write_bytes_total\"),\n\t\t\t\"Total amount of TCP/UDP traffic written, in bytes.\",\n\t\t\t[]string{\"status_path\"}, nil),\n\t\t\"Auth read bytes\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(\"openvpn\", \"client\", \"auth_read_bytes_total\"),\n\t\t\t\"Total amount of authentication traffic read, in bytes.\",\n\t\t\t[]string{\"status_path\"}, nil),\n\t\t\"pre-compress bytes\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(\"openvpn\", \"client\", \"pre_compress_bytes_total\"),\n\t\t\t\"Total amount of data before compression, in bytes.\",\n\t\t\t[]string{\"status_path\"}, nil),\n\t\t\"post-compress bytes\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(\"openvpn\", \"client\", \"post_compress_bytes_total\"),\n\t\t\t\"Total amount of data after compression, in bytes.\",\n\t\t\t[]string{\"status_path\"}, nil),\n\t\t\"pre-decompress bytes\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(\"openvpn\", \"client\", \"pre_decompress_bytes_total\"),\n\t\t\t\"Total amount of data before decompression, in bytes.\",\n\t\t\t[]string{\"status_path\"}, nil),\n\t\t\"post-decompress bytes\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(\"openvpn\", \"client\", \"post_decompress_bytes_total\"),\n\t\t\t\"Total amount of data after decompression, in bytes.\",\n\t\t\t[]string{\"status_path\"}, nil),\n\t}\n\n\tvar serverHeaderClientLabels []string\n\tvar serverHeaderClientLabelColumns []string\n\tvar serverHeaderRoutingLabels []string\n\tvar serverHeaderRoutingLabelColumns []string\n\tif ignoreIndividuals {\n\t\tserverHeaderClientLabels = []string{\"status_path\", \"common_name\"}\n\t\tserverHeaderClientLabelColumns = []string{\"Common Name\"}\n\t\tserverHeaderRoutingLabels = []string{\"status_path\", \"common_name\"}\n\t\tserverHeaderRoutingLabelColumns = []string{\"Common Name\"}\n\t} else {\n\t\tserverHeaderClientLabels = []string{\"status_path\", \"common_name\", \"connection_time\", \"real_address\", \"virtual_address\", \"username\"}\n\t\tserverHeaderClientLabelColumns = []string{\"Common Name\", \"Connected Since (time_t)\", \"Real Address\", \"Virtual Address\", \"Username\"}\n\t\tserverHeaderRoutingLabels = []string{\"status_path\", \"common_name\", \"real_address\", \"virtual_address\"}\n\t\tserverHeaderRoutingLabelColumns = []string{\"Common Name\", \"Real Address\", \"Virtual Address\"}\n\t}\n\n\topenvpnServerHeaders := map[string]OpenvpnServerHeader{\n\t\t\"CLIENT_LIST\": {\n\t\t\tLabelColumns: serverHeaderClientLabelColumns,\n\t\t\tMetrics: []OpenvpnServerHeaderField{\n\t\t\t\t{\n\t\t\t\t\tColumn: \"Bytes Received\",\n\t\t\t\t\tDesc: prometheus.NewDesc(\n\t\t\t\t\t\tprometheus.BuildFQName(\"openvpn\", \"server\", \"client_received_bytes_total\"),\n\t\t\t\t\t\t\"Amount of data received over a connection on the VPN server, in bytes.\",\n\t\t\t\t\t\tserverHeaderClientLabels, nil),\n\t\t\t\t\tValueType: prometheus.CounterValue,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tColumn: \"Bytes Sent\",\n\t\t\t\t\tDesc: prometheus.NewDesc(\n\t\t\t\t\t\tprometheus.BuildFQName(\"openvpn\", \"server\", \"client_sent_bytes_total\"),\n\t\t\t\t\t\t\"Amount of data sent over a connection on the VPN server, in bytes.\",\n\t\t\t\t\t\tserverHeaderClientLabels, nil),\n\t\t\t\t\tValueType: prometheus.CounterValue,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"ROUTING_TABLE\": {\n\t\t\tLabelColumns: serverHeaderRoutingLabelColumns,\n\t\t\tMetrics: []OpenvpnServerHeaderField{\n\t\t\t\t{\n\t\t\t\t\tColumn: \"Last Ref (time_t)\",\n\t\t\t\t\tDesc: prometheus.NewDesc(\n\t\t\t\t\t\tprometheus.BuildFQName(\"openvpn\", \"server\", \"route_last_reference_time_seconds\"),\n\t\t\t\t\t\t\"Time at which a route was last referenced, in seconds.\",\n\t\t\t\t\t\tserverHeaderRoutingLabels, nil),\n\t\t\t\t\tValueType: prometheus.GaugeValue,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn &OpenVPNExporter{\n\t\tstatusPaths:                 statusPaths,\n\t\topenvpnUpDesc:               openvpnUpDesc,\n\t\topenvpnStatusUpdateTimeDesc: openvpnStatusUpdateTimeDesc,\n\t\topenvpnConnectedClientsDesc: openvpnConnectedClientsDesc,\n\t\topenvpnClientDescs:          openvpnClientDescs,\n\t\topenvpnServerHeaders:        openvpnServerHeaders,\n\t}, nil\n}\n\n// Converts OpenVPN status information into Prometheus metrics. This\n// function automatically detects whether the file contains server or\n// client metrics. For server metrics, it also distinguishes between the\n// version 2 and 3 file formats.\nfunc (e *OpenVPNExporter) collectStatusFromReader(statusPath string, file io.Reader, ch chan<- prometheus.Metric) error {\n\treader := bufio.NewReader(file)\n\tbuf, _ := reader.Peek(18)\n\tif bytes.HasPrefix(buf, []byte(\"TITLE,\")) {\n\t\t// Server statistics, using format version 2.\n\t\treturn e.collectServerStatusFromReader(statusPath, reader, ch, \",\")\n\t} else if bytes.HasPrefix(buf, []byte(\"TITLE\\t\")) {\n\t\t// Server statistics, using format version 3. The only\n\t\t// difference compared to version 2 is that it uses tabs\n\t\t// instead of spaces.\n\t\treturn e.collectServerStatusFromReader(statusPath, reader, ch, \"\\t\")\n\t} else if bytes.HasPrefix(buf, []byte(\"OpenVPN STATISTICS\")) {\n\t\t// Client statistics.\n\t\treturn e.collectClientStatusFromReader(statusPath, reader, ch)\n\t} else {\n\t\treturn fmt.Errorf(\"unexpected file contents: %q\", buf)\n\t}\n}\n\n// Converts OpenVPN server status information into Prometheus metrics.\nfunc (e *OpenVPNExporter) collectServerStatusFromReader(statusPath string, file io.Reader, ch chan<- prometheus.Metric, separator string) error {\n\tscanner := bufio.NewScanner(file)\n\tscanner.Split(bufio.ScanLines)\n\theadersFound := map[string][]string{}\n\t// counter of connected client\n\tnumberConnectedClient := 0\n\n\trecordedMetrics := map[OpenvpnServerHeaderField][]string{}\n\n\tfor scanner.Scan() {\n\t\tfields := strings.Split(scanner.Text(), separator)\n\t\tif fields[0] == \"END\" && len(fields) == 1 {\n\t\t\t// Stats footer.\n\t\t} else if fields[0] == \"GLOBAL_STATS\" {\n\t\t\t// Global server statistics.\n\t\t} else if fields[0] == \"HEADER\" && len(fields) > 2 {\n\t\t\t// Column names for CLIENT_LIST and ROUTING_TABLE.\n\t\t\theadersFound[fields[1]] = fields[2:]\n\t\t} else if fields[0] == \"TIME\" && len(fields) == 3 {\n\t\t\t// Time at which the statistics were updated.\n\t\t\ttimeStartStats, err := strconv.ParseFloat(fields[2], 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\te.openvpnStatusUpdateTimeDesc,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\ttimeStartStats,\n\t\t\t\tstatusPath)\n\t\t} else if fields[0] == \"TITLE\" && len(fields) == 2 {\n\t\t\t// OpenVPN version number.\n\t\t} else if header, ok := e.openvpnServerHeaders[fields[0]]; ok {\n\t\t\tif fields[0] == \"CLIENT_LIST\" {\n\t\t\t\tnumberConnectedClient++\n\t\t\t}\n\t\t\t// Entry that depends on a preceding HEADERS directive.\n\t\t\tcolumnNames, ok := headersFound[fields[0]]\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"%s should be preceded by HEADERS\", fields[0])\n\t\t\t}\n\t\t\tif len(fields) != len(columnNames)+1 {\n\t\t\t\treturn fmt.Errorf(\"HEADER for %s describes a different number of columns\", fields[0])\n\t\t\t}\n\n\t\t\t// Store entry values in a map indexed by column name.\n\t\t\tcolumnValues := map[string]string{}\n\t\t\tfor _, column := range header.LabelColumns {\n\t\t\t\tcolumnValues[column] = \"\"\n\t\t\t}\n\t\t\tfor i, column := range columnNames {\n\t\t\t\tcolumnValues[column] = fields[i+1]\n\t\t\t}\n\n\t\t\t// Extract columns that should act as entry labels.\n\t\t\tlabels := []string{statusPath}\n\t\t\tfor _, column := range header.LabelColumns {\n\t\t\t\tlabels = append(labels, columnValues[column])\n\t\t\t}\n\n\t\t\t// Export relevant columns as individual metrics.\n\t\t\tfor _, metric := range header.Metrics {\n\t\t\t\tif columnValue, ok := columnValues[metric.Column]; ok {\n\t\t\t\t\tif l, _ := recordedMetrics[metric]; ! subslice(labels, l) {\n\t\t\t\t\t\tvalue, err := strconv.ParseFloat(columnValue, 64)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\t\t\tmetric.Desc,\n\t\t\t\t\t\t\tmetric.ValueType,\n\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\tlabels...)\n\t\t\t\t\t\trecordedMetrics[metric] = append(recordedMetrics[metric], labels...)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Printf(\"Metric entry with same labels: %s, %s\", metric.Column, labels)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"unsupported key: %q\", fields[0])\n\t\t}\n\t}\n\t// add the number of connected client\n\tch <- prometheus.MustNewConstMetric(\n\t\te.openvpnConnectedClientsDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(numberConnectedClient),\n\t\tstatusPath)\n\treturn scanner.Err()\n}\n\n// Does slice contain string\nfunc contains(s []string, e string) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// Is a sub-slice of slice\nfunc subslice(sub []string, main []string) bool {\n\tif len(sub) > len(main) {return false}\n\tfor _, s := range sub {\n\t\tif ! contains(main, s) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Converts OpenVPN client status information into Prometheus metrics.\nfunc (e *OpenVPNExporter) collectClientStatusFromReader(statusPath string, file io.Reader, ch chan<- prometheus.Metric) error {\n\tscanner := bufio.NewScanner(file)\n\tscanner.Split(bufio.ScanLines)\n\tfor scanner.Scan() {\n\t\tfields := strings.Split(scanner.Text(), \",\")\n\t\tif fields[0] == \"END\" && len(fields) == 1 {\n\t\t\t// Stats footer.\n\t\t} else if fields[0] == \"OpenVPN STATISTICS\" && len(fields) == 1 {\n\t\t\t// Stats header.\n\t\t} else if fields[0] == \"Updated\" && len(fields) == 2 {\n\t\t\t// Time at which the statistics were updated.\n\t\t\tlocation, _ := time.LoadLocation(\"Local\")\n\t\t\ttimeParser, err := time.ParseInLocation(\"Mon Jan 2 15:04:05 2006\", fields[1], location)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\te.openvpnStatusUpdateTimeDesc,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tfloat64(timeParser.Unix()),\n\t\t\t\tstatusPath)\n\t\t} else if desc, ok := e.openvpnClientDescs[fields[0]]; ok && len(fields) == 2 {\n\t\t\t// Traffic counters.\n\t\t\tvalue, err := strconv.ParseFloat(fields[1], 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tdesc,\n\t\t\t\tprometheus.CounterValue,\n\t\t\t\tvalue,\n\t\t\t\tstatusPath)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"unsupported key: %q\", fields[0])\n\t\t}\n\t}\n\treturn scanner.Err()\n}\n\nfunc (e *OpenVPNExporter) collectStatusFromFile(statusPath string, ch chan<- prometheus.Metric) error {\n\tconn, err := os.Open(statusPath)\n\tdefer conn.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn e.collectStatusFromReader(statusPath, conn, ch)\n}\n\nfunc (e *OpenVPNExporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- e.openvpnUpDesc\n}\n\nfunc (e *OpenVPNExporter) Collect(ch chan<- prometheus.Metric) {\n\tfor _, statusPath := range e.statusPaths {\n\t\terr := e.collectStatusFromFile(statusPath, ch)\n\t\tif err == nil {\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\te.openvpnUpDesc,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\t1.0,\n\t\t\t\tstatusPath)\n\t\t} else {\n\t\t\tlog.Printf(\"Failed to scrape showq socket: %s\", err)\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\te.openvpnUpDesc,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\t0.0,\n\t\t\t\tstatusPath)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/kumina/openvpn_exporter\n\nrequire (\n\tgithub.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 // indirect\n\tgithub.com/gogo/protobuf v1.1.1 // indirect\n\tgithub.com/golang/protobuf v1.2.0 // indirect\n\tgithub.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect\n\tgithub.com/prometheus/client_golang v0.9.1\n\tgithub.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 // indirect\n\tgithub.com/prometheus/common v0.0.0-20181020173914-7e9e6cabbd39 // indirect\n\tgithub.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d // indirect\n\tgolang.org/x/sync v0.0.0-20181108010431-42b317875d0f // indirect\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0=\ngithub.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=\ngithub.com/gogo/protobuf v1.1.1 h1:72R+M5VuhED/KujmZVcIquuo8mBgX4oVda//DQb3PXo=\ngithub.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=\ngithub.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=\ngithub.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=\ngithub.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=\ngithub.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=\ngithub.com/prometheus/client_golang v0.9.1 h1:K47Rk0v/fkEfwfQet2KWhscE0cJzjgCCDBG2KHZoVno=\ngithub.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=\ngithub.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 h1:idejC8f05m9MGOsuEi1ATq9shN03HrxNkD/luQvxCv8=\ngithub.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=\ngithub.com/prometheus/common v0.0.0-20181020173914-7e9e6cabbd39 h1:Cto4X6SVMWRPBkJ/3YHn1iDGDGc/Z+sW+AEMKHMVvN4=\ngithub.com/prometheus/common v0.0.0-20181020173914-7e9e6cabbd39/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=\ngithub.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d h1:GoAlyOgbOEIFdaDqxJVlbOQ1DtGmZWs/Qau0hIlk+WQ=\ngithub.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=\ngolang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ=\ngolang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\n"
  },
  {
    "path": "main.go",
    "content": "// Copyright 2017 Kumina, https://kumina.nl/\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"github.com/kumina/openvpn_exporter/exporters\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc main() {\n\tvar (\n\t\tlistenAddress      = flag.String(\"web.listen-address\", \":9176\", \"Address to listen on for web interface and telemetry.\")\n\t\tmetricsPath        = flag.String(\"web.telemetry-path\", \"/metrics\", \"Path under which to expose metrics.\")\n\t\topenvpnStatusPaths = flag.String(\"openvpn.status_paths\", \"examples/client.status,examples/server2.status,examples/server3.status\", \"Paths at which OpenVPN places its status files.\")\n\t\tignoreIndividuals  = flag.Bool(\"ignore.individuals\", false, \"If ignoring metrics for individuals\")\n\t)\n\tflag.Parse()\n\n\tlog.Printf(\"Starting OpenVPN Exporter\\n\")\n\tlog.Printf(\"Listen address: %v\\n\", *listenAddress)\n\tlog.Printf(\"Metrics path: %v\\n\", *metricsPath)\n\tlog.Printf(\"openvpn.status_path: %v\\n\", *openvpnStatusPaths)\n\tlog.Printf(\"Ignore Individuals: %v\\n\", *ignoreIndividuals)\n\n\texporter, err := exporters.NewOpenVPNExporter(strings.Split(*openvpnStatusPaths, \",\"), *ignoreIndividuals)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tprometheus.MustRegister(exporter)\n\n\thttp.Handle(*metricsPath, promhttp.Handler())\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(`\n\t\t\t<html>\n\t\t\t<head><title>OpenVPN Exporter</title></head>\n\t\t\t<body>\n\t\t\t<h1>OpenVPN Exporter</h1>\n\t\t\t<p><a href='` + *metricsPath + `'>Metrics</a></p>\n\t\t\t</body>\n\t\t\t</html>`))\n\t})\n\tlog.Fatal(http.ListenAndServe(*listenAddress, nil))\n}\n"
  }
]