├── .github └── workflows │ └── build.yml ├── Dockerfile ├── LICENSE ├── README.md ├── deploy ├── ds.yaml └── rbac.yaml ├── go.mod ├── go.sum ├── main.go └── pkg ├── docker └── docker.go ├── kubelet └── client.go ├── metrics └── metrics.go └── netstat └── netstat.go /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | tags: 8 | - v* 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - uses: azure/docker-login@v1 16 | with: 17 | login-server: quay.io 18 | username: '${{ secrets.QUAYIO_USERNAME }}' 19 | password: '${{ secrets.QUAYIO_PASSWORD }}' 20 | - name: Set up Docker Buildx 21 | id: buildx 22 | uses: crazy-max/ghaction-docker-buildx@v1 23 | with: 24 | buildx-version: latest 25 | qemu-version: latest 26 | - name: Available platforms 27 | run: 'echo ${{ steps.buildx.outputs.platforms }}' 28 | - name: Run Buildx 29 | run: | 30 | docker buildx build \ 31 | --platform linux/amd64,linux/arm64 \ 32 | --push -t quay.io/wish/pod-netstat-exporter:${GITHUB_REF##*/} . 33 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM --platform=$BUILDPLATFORM golang:1.14 2 | 3 | ARG BUILDPLATFORM 4 | ARG TARGETARCH 5 | ARG TARGETOS 6 | 7 | ENV GO111MODULE=on 8 | WORKDIR /go/src/github.com/wish/pod-netstat-exporter 9 | 10 | # Cache dependencies 11 | COPY go.mod . 12 | COPY go.sum . 13 | RUN go mod download 14 | 15 | COPY . /go/src/github.com/wish/pod-netstat-exporter/ 16 | 17 | RUN CGO_ENABLED=0 GOARCH=${TARGETARCH} GOOS=${TARGETOS} go build -o ./pod-netstat-exporter -a -installsuffix cgo . 18 | 19 | FROM alpine:3.11 20 | RUN apk --no-cache add ca-certificates 21 | WORKDIR /root/ 22 | COPY --from=0 /go/src/github.com/wish/pod-netstat-exporter/pod-netstat-exporter /root/pod-netstat-exporter 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 ContextLogic Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pod-netstat-exporter [![GoDoc](https://godoc.org/github.com/wish/pod-netstat-exporter?status.svg)](https://godoc.org/github.com/wish/pod-netstat-exporter) [![Go Report Card](https://goreportcard.com/badge/github.com/wish/pod-netstat-exporter)](https://goreportcard.com/report/github.com/wish/pod-netstat-exporter) [![Docker Repository on Quay](https://quay.io/repository/wish/pod-netstat-exporter/status "Docker Repository on Quay")](https://quay.io/repository/wish/pod-netstat-exporter) 2 | 3 | Get detailed, per-pod network metrics for export to prometheus. Right now it assumes that: 4 | 5 | - You are using kubernetes, and the local kubelet API is accessible 6 | - You are using docker 7 | 8 | ## Limitations 9 | 10 | For the most part, a k8s pod maps 1-to-1 to a linux network namespace. This however is not 11 | the case if the pod is using `hostNetwork: true`. In that case, the pod uses the default 12 | network namespace of the host, and there are no per-pod metrics to collect. Rather than 13 | report something misleading, `pod-netstat-exporter` just doesn't return any metrics for those 14 | pods. 15 | -------------------------------------------------------------------------------- /deploy/ds.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apps/v1 3 | kind: DaemonSet 4 | metadata: 5 | labels: 6 | app: pod-netstat-exporter 7 | name: pod-netstat-exporter 8 | namespace: pod-netstat-exporter 9 | spec: 10 | selector: 11 | matchLabels: 12 | app: pod-netstat-exporter 13 | template: 14 | metadata: 15 | labels: 16 | app: pod-netstat-exporter 17 | spec: 18 | serviceAccountName: pod-netstat-exporter 19 | hostNetwork: true 20 | hostPID: true 21 | tolerations: 22 | - key: 'node-role.kubernetes.io/master' 23 | effect: 'NoSchedule' 24 | - key: 'CriticalAddonsOnly' 25 | operator: 'Exists' 26 | containers: 27 | - name: pod-netstat-exporter 28 | image: quay.io/wish/pod-netstat-exporter:latest 29 | imagePullPolicy: Always 30 | command: ['/root/pod-netstat-exporter'] 31 | env: 32 | - name: 'KUBELET_API' 33 | value: 'https://localhost:10250/pods' 34 | - name: 'KUBELET_API_INSECURE_SKIP_VERIFY' 35 | value: 'true' 36 | - name: BIND_ADDRESS 37 | value: ':9657' 38 | - name: RATE_LIMIT 39 | value: '3' 40 | - name: HOST_MOUNT_PATH 41 | value: '/host' 42 | ports: 43 | - name: 'metrics' 44 | containerPort: 9657 45 | protocol: 'TCP' 46 | livenessProbe: 47 | httpGet: 48 | path: '/' 49 | port: 9657 50 | readinessProbe: 51 | httpGet: 52 | path: '/' 53 | port: 9657 54 | volumeMounts: 55 | - name: 'hproc' 56 | mountPath: '/host/proc' 57 | - name: 'hsys' 58 | mountPath: '/host/sys' 59 | - name: 'hvr' 60 | mountPath: '/host/var/run' 61 | volumes: 62 | - name: 'hproc' 63 | hostPath: 64 | path: '/proc' 65 | - name: 'hsys' 66 | hostPath: 67 | path: '/sys' 68 | - name: 'hvr' 69 | hostPath: 70 | path: '/var/run' 71 | -------------------------------------------------------------------------------- /deploy/rbac.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Namespace 4 | metadata: 5 | name: pod-netstat-exporter 6 | --- 7 | apiVersion: v1 8 | kind: ServiceAccount 9 | metadata: 10 | name: pod-netstat-exporter 11 | namespace: pod-netstat-exporter 12 | labels: 13 | app: pod-netstat-exporter 14 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/wish/pod-netstat-exporter 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d // indirect 7 | github.com/jessevdk/go-flags v1.4.0 8 | github.com/json-iterator/go v1.1.7 // indirect 9 | github.com/kr/pretty v0.1.0 // indirect 10 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 11 | github.com/prometheus/common v0.7.0 12 | github.com/sirupsen/logrus v1.4.2 13 | github.com/spf13/pflag v1.0.3 // indirect 14 | golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc // indirect 15 | golang.org/x/net v0.0.0-20190812203447-cdfb69ac37fc // indirect 16 | golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 // indirect 17 | golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f // indirect 18 | golang.org/x/text v0.3.2 // indirect 19 | golang.org/x/time v0.0.0-20190921001708-c4c64cad1fd0 20 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect 21 | gopkg.in/inf.v0 v0.9.0 // indirect 22 | gopkg.in/yaml.v2 v2.2.4 // indirect 23 | k8s.io/api v0.0.0-20181204000039-89a74a8d264d 24 | k8s.io/apimachinery v0.0.0-20181127025237-2b1284ed4c93 // indirect 25 | k8s.io/client-go v10.0.0+incompatible 26 | k8s.io/klog v1.0.0 // indirect 27 | sigs.k8s.io/yaml v1.1.0 // indirect 28 | ) 29 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 3 | github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 4 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 5 | github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 6 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 7 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= 8 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 9 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 10 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 11 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 12 | github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 13 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= 14 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= 15 | github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= 16 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= 17 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 18 | github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d h1:3PaI8p3seN09VjbTYC/QWlUZdZ1qS1zGjy7LH2Wt07I= 19 | github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= 20 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 21 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 22 | github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= 23 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 24 | github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= 25 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 26 | github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA= 27 | github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= 28 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= 29 | github.com/json-iterator/go v1.1.7 h1:KfgG9LzI+pYjr4xvmz/5H4FXjokeP+rlHLhv3iH62Fo= 30 | github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 31 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 32 | github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= 33 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= 34 | github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= 35 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 36 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= 37 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 38 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 39 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 40 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 41 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 42 | github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= 43 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 44 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 45 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 46 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 47 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 48 | github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= 49 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 50 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= 51 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 52 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 53 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 54 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 55 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 56 | github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= 57 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 58 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 59 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM= 60 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 61 | github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= 62 | github.com/prometheus/common v0.7.0 h1:L+1lyG48J1zAQXA3RBX/nG/B3gjlHq0zTt2tlbJLyCY= 63 | github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= 64 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 65 | github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= 66 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= 67 | github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= 68 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= 69 | github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= 70 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 71 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 72 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 73 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 74 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= 75 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 76 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 77 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 78 | golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc h1:c0o/qxkaO2LF5t6fQrT4b5hzyggAkLLlCUjqfRxd8Q4= 79 | golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 80 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 81 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 82 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 83 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 84 | golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 85 | golang.org/x/net v0.0.0-20190812203447-cdfb69ac37fc h1:gkKoSkUmnU6bpS/VhkuO27bzQeSA51uaEfbOW5dNb68= 86 | golang.org/x/net v0.0.0-20190812203447-cdfb69ac37fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 87 | golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= 88 | golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= 89 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 90 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 91 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 92 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 93 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 94 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 95 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 96 | golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f h1:25KHgbfyiSm6vwQLbM3zZIe1v9p/3ea4Rz+nnM5K/i4= 97 | golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 98 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 99 | golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= 100 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 101 | golang.org/x/time v0.0.0-20190921001708-c4c64cad1fd0 h1:xQwXv67TxFo9nC1GJFyab5eq/5B590r6RlnL/G8Sz7w= 102 | golang.org/x/time v0.0.0-20190921001708-c4c64cad1fd0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 103 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 104 | golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 105 | google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= 106 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 107 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 108 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 109 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= 110 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 111 | gopkg.in/inf.v0 v0.9.0 h1:3zYtXIO92bvsdS3ggAdA8Gb4Azj0YU+TVY1uGYNFA8o= 112 | gopkg.in/inf.v0 v0.9.0/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= 113 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 114 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 115 | gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= 116 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 117 | k8s.io/api v0.0.0-20181204000039-89a74a8d264d h1:HQoGWsWUe/FmRcX9BU440AAMnzBFEf+DBo4nbkQlNzs= 118 | k8s.io/api v0.0.0-20181204000039-89a74a8d264d/go.mod h1:iuAfoD4hCxJ8Onx9kaTIt30j7jUFS00AXQi6QMi99vA= 119 | k8s.io/apimachinery v0.0.0-20181127025237-2b1284ed4c93 h1:tT6oQBi0qwLbbZSfDkdIsb23EwaLY85hoAV4SpXfdao= 120 | k8s.io/apimachinery v0.0.0-20181127025237-2b1284ed4c93/go.mod h1:ccL7Eh7zubPUSh9A3USN90/OzHNSVN6zxzde07TDCL0= 121 | k8s.io/client-go v10.0.0+incompatible h1:F1IqCqw7oMBzDkqlcBymRq1450wD0eNqLE9jzUrIi34= 122 | k8s.io/client-go v10.0.0+incompatible/go.mod h1:7vJpHMYJwNQCWgzmNV+VYUl1zCObLyodBc8nIyt8L5s= 123 | k8s.io/klog v1.0.0 h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8= 124 | k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= 125 | sigs.k8s.io/yaml v1.1.0 h1:4A07+ZFc2wgJwo8YNlQpr1rVlgUDlxXHhPJciaPY5gs= 126 | sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= 127 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | "os" 8 | "os/signal" 9 | "syscall" 10 | 11 | "github.com/jessevdk/go-flags" 12 | "github.com/sirupsen/logrus" 13 | "golang.org/x/time/rate" 14 | core_v1 "k8s.io/api/core/v1" 15 | 16 | "github.com/wish/pod-netstat-exporter/pkg/docker" 17 | "github.com/wish/pod-netstat-exporter/pkg/kubelet" 18 | "github.com/wish/pod-netstat-exporter/pkg/metrics" 19 | "github.com/wish/pod-netstat-exporter/pkg/netstat" 20 | ) 21 | 22 | type ops struct { 23 | kubelet.ClientConfig 24 | LogLevel string `long:"log-level" env:"LOG_LEVEL" description:"Log level" default:"info"` 25 | RateLimit float64 `long:"rate-limit" env:"RATE_LIMIT" description:"The number of /metrics requests served per second" default:"3"` 26 | BindAddr string `long:"bind-address" short:"p" env:"BIND_ADDRESS" default:":9657" description:"address for binding metrics listener"` 27 | HostMountPath string `long:"host-mount-path" env:"HOST_MOUNT_PATH" default:"/host" description:"The path where the host filesystem is mounted"` 28 | } 29 | 30 | func setupLogging(logLevel string) { 31 | // Use log level 32 | level, err := logrus.ParseLevel(logLevel) 33 | if err != nil { 34 | logrus.Fatalf("Unknown log level %s: %v", logLevel, err) 35 | } 36 | logrus.SetLevel(level) 37 | 38 | // Set the log format to have a reasonable timestamp 39 | formatter := &logrus.TextFormatter{ 40 | FullTimestamp: true, 41 | } 42 | logrus.SetFormatter(formatter) 43 | } 44 | 45 | // All containers in a pod share the same netns, so get the PID and then the statistics 46 | // from the first pod 47 | func getPodNetstats(opts *ops, pod *core_v1.Pod) (*netstat.NetStats, error) { 48 | logrus.Tracef("Getting stats for pod %v", pod.Name) 49 | if len(pod.Status.ContainerStatuses) == 0 { 50 | return nil, fmt.Errorf("No containers in pod") 51 | } 52 | container := pod.Status.ContainerStatuses[0].ContainerID 53 | pid, err := docker.ContainerToPID(opts.HostMountPath, container) 54 | if err != nil { 55 | return nil, fmt.Errorf("Error getting pid for container %v: %v", container, err) 56 | } 57 | logrus.Tracef("Container %v of pod %v has PID %v", container, pod.Name, pid) 58 | stats, err := netstat.GetStats(opts.HostMountPath, pid) 59 | return &stats, err 60 | } 61 | 62 | func allPodStats(opts *ops, client *kubelet.Client) ([]*metrics.PodStats, error) { 63 | podStats := []*metrics.PodStats{} 64 | 65 | p, err := client.GetPodList() 66 | if err != nil { 67 | return podStats, fmt.Errorf("Error getting pod list: %v", err) 68 | } 69 | 70 | // Actually fetch the per-pod statistics 71 | for _, pod := range p.Items { 72 | if pod.Spec.HostNetwork { 73 | logrus.Tracef("Pod %v has hostNetwork: true, cannot fetch per-pod network metrics", pod.Name) 74 | continue 75 | } 76 | 77 | stats, err := getPodNetstats(opts, &pod) 78 | if err != nil { 79 | logrus.Warnf("Could not get stats for pod %v: %v", pod.Name, err) 80 | continue 81 | } 82 | podStats = append(podStats, &metrics.PodStats{ 83 | NetStats: *stats, 84 | Name: pod.Name, 85 | Namespace: pod.Namespace, 86 | }) 87 | } 88 | 89 | return podStats, nil 90 | } 91 | 92 | func main() { 93 | opts := &ops{} 94 | parser := flags.NewParser(opts, flags.Default) 95 | if _, err := parser.Parse(); err != nil { 96 | // If the error was from the parser, then we can simply return 97 | // as Parse() prints the error already 98 | if _, ok := err.(*flags.Error); ok { 99 | os.Exit(1) 100 | } 101 | logrus.Fatalf("Error parsing flags: %v", err) 102 | } 103 | setupLogging(opts.LogLevel) 104 | 105 | client, err := kubelet.NewClient(opts.ClientConfig) 106 | if err != nil { 107 | logrus.Fatal(err) 108 | } 109 | 110 | srv := &http.Server{ 111 | Addr: opts.BindAddr, 112 | } 113 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 114 | fmt.Fprintf(w, "OK\n") 115 | }) 116 | http.HandleFunc("/healthcheck", func(w http.ResponseWriter, r *http.Request) { 117 | fmt.Fprintf(w, "OK\n") 118 | }) 119 | 120 | metricsLimiter := rate.NewLimiter(rate.Limit(opts.RateLimit), 5) 121 | http.HandleFunc("/metrics", func(rsp http.ResponseWriter, req *http.Request) { 122 | if metricsLimiter.Allow() == false { 123 | http.Error(rsp, http.StatusText(429), http.StatusTooManyRequests) 124 | return 125 | } 126 | 127 | stats, err := allPodStats(opts, client) 128 | if err != nil { 129 | logrus.Error(err) 130 | metrics.HTTPError(rsp, err) 131 | return 132 | } 133 | 134 | metrics.Handler(rsp, req, stats) 135 | }) 136 | go func() { 137 | if err := srv.ListenAndServe(); err != nil { 138 | logrus.Errorf("Error serving HTTP at %v: %v", opts.BindAddr, err) 139 | } 140 | }() 141 | 142 | stopCh := make(chan struct{}) 143 | defer close(stopCh) 144 | 145 | sigterm := make(chan os.Signal, 1) 146 | signal.Notify(sigterm, syscall.SIGTERM) 147 | signal.Notify(sigterm, syscall.SIGINT) 148 | <-sigterm 149 | 150 | logrus.Info("Received SIGTERM or SIGINT. Shutting down.") 151 | srv.Shutdown(context.Background()) 152 | } 153 | -------------------------------------------------------------------------------- /pkg/docker/docker.go: -------------------------------------------------------------------------------- 1 | package docker 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "path/filepath" 7 | "strconv" 8 | "strings" 9 | 10 | "github.com/sirupsen/logrus" 11 | ) 12 | 13 | // ContainerToPID finds the PID of the given container 14 | func ContainerToPID(hostMountPath, container string) (int, error) { 15 | raw := strings.Replace(container, "docker://", "", 1) 16 | return getPidForContainer(hostMountPath, raw) 17 | } 18 | 19 | // Everything below this point is modified from 20 | // https://github.com/vishvananda/netns 21 | // which according to the comments was mostly borrowed from 22 | // the docker source code anyway 23 | /////////////////////////////////////////////////////////////////////// 24 | 25 | // borrowed from docker/utils/utils.go 26 | func findCgroupMountpoint(hostMountPath, cgroupType string) (string, error) { 27 | output, err := ioutil.ReadFile(hostMountPath + "/proc/mounts") 28 | if err != nil { 29 | return "", err 30 | } 31 | 32 | // /proc/mounts has 6 fields per line, one mount per line, e.g. 33 | // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0 34 | for _, line := range strings.Split(string(output), "\n") { 35 | parts := strings.Split(line, " ") 36 | if len(parts) == 6 && parts[2] == "cgroup" { 37 | for _, opt := range strings.Split(parts[3], ",") { 38 | if opt == cgroupType { 39 | return parts[1], nil 40 | } 41 | } 42 | } 43 | } 44 | 45 | return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType) 46 | } 47 | 48 | // Returns the relative path to the cgroup docker is running in. 49 | // borrowed from docker/utils/utils.go 50 | // modified to get the docker pid instead of using /proc/self 51 | func getThisCgroup(hostMountPath, cgroupType string) (string, error) { 52 | dockerpid, err := ioutil.ReadFile(hostMountPath + "/var/run/docker.pid") 53 | if err != nil { 54 | return "", err 55 | } 56 | result := strings.Split(string(dockerpid), "\n") 57 | if len(result) == 0 || len(result[0]) == 0 { 58 | return "", fmt.Errorf("docker pid not found in %s/var/run/docker.pid", hostMountPath) 59 | } 60 | pid, err := strconv.Atoi(result[0]) 61 | if err != nil { 62 | return "", err 63 | } 64 | output, err := ioutil.ReadFile(fmt.Sprintf(hostMountPath+"/proc/%d/cgroup", pid)) 65 | if err != nil { 66 | return "", err 67 | } 68 | for _, line := range strings.Split(string(output), "\n") { 69 | parts := strings.Split(line, ":") 70 | // any type used by docker should work 71 | if parts[1] == cgroupType { 72 | return parts[2], nil 73 | } 74 | } 75 | return "", fmt.Errorf("cgroup '%s' not found in %s/proc/%d/cgroup", cgroupType, hostMountPath, pid) 76 | } 77 | 78 | // Returns the first pid in a container. 79 | // borrowed from docker/utils/utils.go 80 | // modified to only return the first pid 81 | // modified to glob with id 82 | // modified to search for newer docker containers 83 | func getPidForContainer(hostMountPath, id string) (int, error) { 84 | pid := 0 85 | 86 | // memory is chosen randomly, any cgroup used by docker works 87 | cgroupType := "memory" 88 | 89 | cgroupRoot, err := findCgroupMountpoint(hostMountPath, cgroupType) 90 | if err != nil { 91 | return pid, err 92 | } 93 | 94 | cgroupThis, err := getThisCgroup(hostMountPath, cgroupType) 95 | if err != nil { 96 | return pid, err 97 | } 98 | 99 | id += "*" 100 | 101 | attempts := []string{ 102 | // Kubernetes with docker and CNI is even more different 103 | filepath.Join(hostMountPath, cgroupRoot, "..", "systemd", "kubepods", "*", "pod*", id, "tasks"), 104 | // Another flavor of containers location in recent kubernetes 1.11+ 105 | filepath.Join(hostMountPath, cgroupRoot, cgroupThis, "kubepods.slice", "kubepods-besteffort.slice", "*", "docker-"+id+".scope", "tasks"), 106 | // When runs inside of a container with recent kubernetes 1.11+ 107 | filepath.Join(hostMountPath, cgroupRoot, "kubepods.slice", "kubepods-besteffort.slice", "*", "docker-"+id+".scope", "tasks"), 108 | filepath.Join(hostMountPath, cgroupRoot, cgroupThis, id, "tasks"), 109 | // With more recent lxc versions use, cgroup will be in lxc/ 110 | filepath.Join(hostMountPath, cgroupRoot, cgroupThis, "lxc", id, "tasks"), 111 | // With more recent docker, cgroup will be in docker/ 112 | filepath.Join(hostMountPath, cgroupRoot, cgroupThis, "docker", id, "tasks"), 113 | // Even more recent docker versions under systemd use docker-.scope/ 114 | filepath.Join(hostMountPath, cgroupRoot, "system.slice", "docker-"+id+".scope", "tasks"), 115 | // Even more recent docker versions under cgroup/systemd/docker// 116 | filepath.Join(hostMountPath, cgroupRoot, "..", "systemd", "docker", id, "tasks"), 117 | } 118 | 119 | var filename string 120 | for _, attempt := range attempts { 121 | filenames, _ := filepath.Glob(attempt) 122 | if len(filenames) > 1 { 123 | return pid, fmt.Errorf("Ambiguous id supplied: %v", filenames) 124 | } else if len(filenames) == 1 { 125 | filename = filenames[0] 126 | break 127 | } 128 | } 129 | 130 | logrus.Tracef("Looking for container %v pid in %v", id, filename) 131 | 132 | if filename == "" { 133 | return pid, fmt.Errorf("Unable to find container: %v", id[:len(id)-1]) 134 | } 135 | 136 | output, err := ioutil.ReadFile(filename) 137 | if err != nil { 138 | return pid, err 139 | } 140 | 141 | result := strings.Split(string(output), "\n") 142 | if len(result) == 0 || len(result[0]) == 0 { 143 | return pid, fmt.Errorf("No pid found for container") 144 | } 145 | 146 | pid, err = strconv.Atoi(result[0]) 147 | if err != nil { 148 | return pid, fmt.Errorf("Invalid pid '%s': %s", result[0], err) 149 | } 150 | 151 | return pid, nil 152 | } 153 | -------------------------------------------------------------------------------- /pkg/kubelet/client.go: -------------------------------------------------------------------------------- 1 | package kubelet 2 | 3 | import ( 4 | "crypto/tls" 5 | "encoding/json" 6 | "io/ioutil" 7 | "net/http" 8 | 9 | k8sApi "k8s.io/api/core/v1" 10 | "k8s.io/client-go/rest" 11 | ) 12 | 13 | // ClientConfig holds the config options for connecting to the kubelet API 14 | type ClientConfig struct { 15 | APIEndpoint string `long:"kubelet-api" env:"KUBELET_API" description:"kubelet API endpoint" default:"http://localhost:10250/pods"` 16 | InsecureSkipVerify bool `long:"kubelet-api-insecure-skip-verify" env:"KUBELET_API_INSECURE_SKIP_VERIFY" description:"skip verification of TLS certificate from kubelet API"` 17 | } 18 | 19 | // NewClient returns a new KubeletClient based on the given config 20 | func NewClient(c ClientConfig) (*Client, error) { 21 | // creates the in-cluster config 22 | config, err := rest.InClusterConfig() 23 | if err != nil { 24 | if err == rest.ErrNotInCluster { 25 | if c.InsecureSkipVerify { 26 | tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} 27 | return &Client{c: c, client: &http.Client{Transport: tr}}, nil 28 | } 29 | 30 | return &Client{c: c, client: http.DefaultClient}, nil 31 | } 32 | return nil, err 33 | } 34 | if c.InsecureSkipVerify { 35 | config.TLSClientConfig.Insecure = true 36 | config.TLSClientConfig.CAData = nil 37 | config.TLSClientConfig.CAFile = "" 38 | } 39 | transport, err := rest.TransportFor(config) 40 | if err != nil { 41 | return nil, err 42 | } 43 | 44 | return &Client{c: c, client: &http.Client{Transport: transport}}, nil 45 | } 46 | 47 | // Client is an HTTP client for kubelet that implements the Kubelet interface 48 | type Client struct { 49 | c ClientConfig 50 | client *http.Client 51 | } 52 | 53 | // GetPodList returns the list of pods the kubelet is managing 54 | func (k *Client) GetPodList() (*k8sApi.PodList, error) { 55 | // k8s testing 56 | req, err := http.NewRequest("GET", k.c.APIEndpoint, nil) 57 | if err != nil { 58 | return nil, err 59 | } 60 | 61 | resp, err := k.client.Do(req) 62 | if err != nil { 63 | return nil, err 64 | } 65 | defer resp.Body.Close() 66 | 67 | var podList k8sApi.PodList 68 | b, err := ioutil.ReadAll(resp.Body) 69 | if err != nil { 70 | return nil, err 71 | } 72 | if err := json.Unmarshal(b, &podList); err != nil { 73 | return nil, err 74 | } 75 | return &podList, nil 76 | } 77 | -------------------------------------------------------------------------------- /pkg/metrics/metrics.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "net/http" 7 | "time" 8 | 9 | dto "github.com/prometheus/client_model/go" 10 | "github.com/prometheus/common/expfmt" 11 | "github.com/sirupsen/logrus" 12 | "github.com/wish/pod-netstat-exporter/pkg/netstat" 13 | ) 14 | 15 | const ( 16 | contentTypeHeader = "Content-Type" 17 | contentEncodingHeader = "Content-Encoding" 18 | ) 19 | 20 | // PodStats represents a pod and the metrics gathered for it 21 | type PodStats struct { 22 | netstat.NetStats 23 | Name string 24 | Namespace string 25 | } 26 | 27 | func s(s string) *string { 28 | return &s 29 | } 30 | 31 | func f(i int64) *float64 { 32 | f := float64(i) 33 | return &f 34 | } 35 | 36 | // generateMetrics creates the actual prometheus metrics from the raw pod stats 37 | func generateMetrics(stats []*PodStats) []*dto.MetricFamily { 38 | timeMs := time.Now().Unix() * int64(time.Second/time.Millisecond) 39 | generateGaugeFamily := func(name, help string) *dto.MetricFamily { 40 | g := dto.MetricType_GAUGE 41 | return &dto.MetricFamily{ 42 | Name: &name, 43 | Help: &help, 44 | Type: &g, 45 | Metric: []*dto.Metric{}, 46 | } 47 | } 48 | 49 | families := map[string]*dto.MetricFamily{} 50 | for _, podStat := range stats { 51 | for metricName, metricValue := range podStat.NetStats { 52 | family, ok := families["pod_netstat_"+metricName] 53 | if !ok { 54 | families["pod_netstat_"+metricName] = generateGaugeFamily( 55 | "pod_netstat_"+metricName, 56 | fmt.Sprintf("The per-pod value of the %v metric from /proc/net/(netstat|snmp|snmp6)", metricName), 57 | ) 58 | family = families["pod_netstat_"+metricName] 59 | } 60 | family.Metric = append(family.Metric, &dto.Metric{ 61 | Label: []*dto.LabelPair{ 62 | &dto.LabelPair{Name: s("pod_namespace"), Value: &podStat.Namespace}, 63 | &dto.LabelPair{Name: s("pod_name"), Value: &podStat.Name}, 64 | }, 65 | Gauge: &dto.Gauge{Value: f(metricValue)}, 66 | TimestampMs: &timeMs, 67 | }) 68 | } 69 | } 70 | 71 | ret := []*dto.MetricFamily{} 72 | for _, metric := range families { 73 | ret = append(ret, metric) 74 | } 75 | return ret 76 | } 77 | 78 | // Handler returns metrics in response to an HTTP request 79 | func Handler(rsp http.ResponseWriter, req *http.Request, stats []*PodStats) { 80 | logrus.Trace("Serving prometheus metrics") 81 | 82 | metrics := generateMetrics(stats) 83 | 84 | contentType := expfmt.Negotiate(req.Header) 85 | header := rsp.Header() 86 | header.Set(contentTypeHeader, string(contentType)) 87 | w := io.Writer(rsp) 88 | enc := expfmt.NewEncoder(w, contentType) 89 | 90 | var lastErr error 91 | for _, mf := range metrics { 92 | if err := enc.Encode(mf); err != nil { 93 | lastErr = err 94 | HTTPError(rsp, err) 95 | return 96 | } 97 | } 98 | 99 | if lastErr != nil { 100 | HTTPError(rsp, lastErr) 101 | } 102 | } 103 | 104 | // HTTPError sends an error as an HTTP response 105 | func HTTPError(rsp http.ResponseWriter, err error) { 106 | rsp.Header().Del(contentEncodingHeader) 107 | http.Error( 108 | rsp, 109 | "An error has occurred while serving metrics:\n\n"+err.Error(), 110 | http.StatusInternalServerError, 111 | ) 112 | } 113 | -------------------------------------------------------------------------------- /pkg/netstat/netstat.go: -------------------------------------------------------------------------------- 1 | package netstat 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "os" 8 | "path" 9 | "strconv" 10 | "strings" 11 | 12 | "github.com/sirupsen/logrus" 13 | ) 14 | 15 | // NetStats is a mapping from stat name to value 16 | type NetStats map[string]int64 17 | 18 | // GetStats returns every netstat from /proc/net/(netstat|snmp|snmp6/sockstat/sockstat6) 19 | func GetStats(rootFs string, pid int) (NetStats, error) { 20 | stats := NetStats{} 21 | nStats, err := netstatsFromProc(rootFs, pid, "net/netstat") 22 | if err != nil { 23 | return stats, err 24 | } 25 | for k, v := range nStats { 26 | stats[k] = v 27 | } 28 | 29 | sStats, err := netstatsFromProc(rootFs, pid, "net/snmp") 30 | if err != nil { 31 | return stats, err 32 | } 33 | for k, v := range sStats { 34 | stats[k] = v 35 | } 36 | 37 | s6Stats, err := snmp6FromProc(rootFs, pid, "net/snmp6") 38 | if err != nil { 39 | return stats, err 40 | } 41 | for k, v := range s6Stats { 42 | stats[k] = v 43 | } 44 | sockStats, err := sockstatsFromProc(rootFs, pid, "net/sockstat") 45 | if err != nil { 46 | return stats, err 47 | } 48 | for k, v := range sockStats { 49 | stats[k] = v 50 | } 51 | sock6Stats, err := sockstatsFromProc(rootFs, pid, "net/sockstat6") 52 | if err != nil { 53 | return stats, err 54 | } 55 | for k, v := range sock6Stats { 56 | stats[k] = v 57 | } 58 | return stats, nil 59 | } 60 | 61 | func netstatsFromProc(rootFs string, pid int, file string) (NetStats, error) { 62 | var err error 63 | var stats NetStats 64 | 65 | statsFile := path.Join(rootFs, "proc", strconv.Itoa(pid), file) 66 | 67 | r, err := os.Open(statsFile) 68 | if err != nil { 69 | return stats, fmt.Errorf("failure opening %s: %v", statsFile, err) 70 | } 71 | 72 | return parseNetStats(r) 73 | } 74 | 75 | // adapted from github.com/prometheus/node_exporter/blob/master/collector/netstat_linux.go 76 | func parseNetStats(r io.Reader) (NetStats, error) { 77 | var ( 78 | netStats = NetStats{} 79 | scanner = bufio.NewScanner(r) 80 | ) 81 | 82 | for scanner.Scan() { 83 | nameParts := strings.Split(scanner.Text(), " ") 84 | if !scanner.Scan() { 85 | logrus.Errorf("Odd number of lines in netstat file") 86 | break 87 | } 88 | valueParts := strings.Split(scanner.Text(), " ") 89 | // Remove trailing :. 90 | protocol := nameParts[0][:len(nameParts[0])-1] 91 | if len(nameParts) != len(valueParts) { 92 | return nil, fmt.Errorf("mismatch field count mismatch: %s", 93 | protocol) 94 | } 95 | for i := 1; i < len(nameParts); i++ { 96 | v, err := strconv.Atoi(valueParts[i]) 97 | if err != nil { 98 | continue 99 | } 100 | 101 | netStats[protocol+"_"+nameParts[i]] = int64(v) 102 | } 103 | } 104 | 105 | return netStats, scanner.Err() 106 | } 107 | 108 | func snmp6FromProc(rootFs string, pid int, file string) (NetStats, error) { 109 | var err error 110 | var stats NetStats 111 | 112 | statsFile := path.Join(rootFs, "proc", strconv.Itoa(pid), file) 113 | 114 | r, err := os.Open(statsFile) 115 | if err != nil { 116 | return stats, fmt.Errorf("failure opening %s: %v", statsFile, err) 117 | } 118 | 119 | return parseSNMP6Stats(r) 120 | } 121 | 122 | // adapted from github.com/prometheus/node_exporter/blob/master/collector/netstat_linux.go 123 | func parseSNMP6Stats(r io.Reader) (NetStats, error) { 124 | var ( 125 | netStats = NetStats{} 126 | scanner = bufio.NewScanner(r) 127 | ) 128 | 129 | for scanner.Scan() { 130 | stat := strings.Fields(scanner.Text()) 131 | if len(stat) < 2 { 132 | continue 133 | } 134 | // Expect to have "6" in metric name, skip line otherwise 135 | if sixIndex := strings.Index(stat[0], "6"); sixIndex != -1 { 136 | protocol := stat[0][:sixIndex+1] 137 | name := stat[0][sixIndex+1:] 138 | v, err := strconv.Atoi(stat[1]) 139 | if err != nil { 140 | continue 141 | } 142 | netStats[protocol+"_"+name] = int64(v) 143 | } 144 | } 145 | 146 | return netStats, scanner.Err() 147 | } 148 | 149 | func sockstatsFromProc(rootFs string, pid int, file string) (NetStats, error) { 150 | var err error 151 | var stats NetStats 152 | 153 | statsFile := path.Join(rootFs, "proc", strconv.Itoa(pid), file) 154 | 155 | r, err := os.Open(statsFile) 156 | if err != nil { 157 | return stats, fmt.Errorf("failure opening %s: %v", statsFile, err) 158 | } 159 | 160 | return parseSockStats(r) 161 | } 162 | func parseSockStats(r io.Reader) (NetStats, error) { 163 | var stats = NetStats{} 164 | s := bufio.NewScanner(r) 165 | for s.Scan() { 166 | fields := strings.Split(s.Text(), " ") 167 | metric := strings.TrimSuffix(fields[0], ":") 168 | if len(fields) < 3 { 169 | return nil, fmt.Errorf("Error: %s", s.Text()) 170 | } 171 | for i := 1; i < len(fields); i++ { 172 | value, err := strconv.Atoi(fields[i+1]) 173 | if err != nil { 174 | continue 175 | } 176 | stats[metric+"_"+fields[i]] = int64(value) 177 | i++ 178 | } 179 | 180 | } 181 | return stats, nil 182 | } 183 | --------------------------------------------------------------------------------