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

OpenVPN Exporter

Metrics

`)) }) log.Fatal(http.ListenAndServe(*listenAddress, nil)) }