refactored, fixed some issues and switched config to yaml
build / build (push) Successful in 1m19s

This commit is contained in:
tchivert committed 2026-01-09 01:28:06 +01:00
1 parent 90cdfa7dec
commit 884a1a92db
7 files changed
+431 -308

No files matched your search

+2 -2
View File
@@ -1,3 +1,3 @@
bin/
prometheus-process-exporter
config-test.json
process-exporter
config-test.yml
+37 -7
View File
@@ -45,20 +45,50 @@ sudo dpkg -i process-exporter-amd64.deb
## Configuration
Create a `config.json` file with the processes you want to monitor:
The exporter uses YAML configuration format, which is the standard for Prometheus exporters.
```json
{
"processes": ["nginx", "haproxy", "postgres"]
}
Create a `config.yml` file with the processes you want to monitor:
```yaml
# Prometheus Process Exporter Configuration
# YAML format - recommended for Prometheus exporters
# List of processes to monitor
processes:
- nginx
- haproxy
- postgres
# - mariadb
# - redis
```
### Configuration Options
- `processes`: List of process names to monitor (required)
- Each process name should be a string in the array
- Comments can be added using `#` prefix
- YAML supports multi-line arrays for better readability
### Example with More Processes
```yaml
processes:
- nginx
- haproxy
- postgres
- mysql
- redis
- docker
- node_exporter
- prometheus
```
## Usage
```bash
Usage of ./prometheus-process-exporter:
Usage of ./process-exporter:
-c string
Path to configuration file (default "config.json")
Path to configuration file (default "config.yml")
-i duration
Interval between metrics collections (e.g., 5s, 1m). 0 means collect on demand only. (default 10s)
-l string
-3
View File
@@ -1,3 +0,0 @@
{
"processes": ["nginx", "haproxy", "postgres"]
}
+10
View File
@@ -0,0 +1,10 @@
# Prometheus Process Exporter Configuration
# YAML format - recommended for Prometheus exporters
# List of processes to monitor
processes:
- nginx
- haproxy
- postgres
# - mysql
# - redis
+15 -13
View File
@@ -1,27 +1,29 @@
module prometheus-process-exporter
module process-exporter
go 1.19
go 1.25.5
require (
github.com/prometheus/client_golang v1.16.0
github.com/shirou/gopsutil/v3 v3.23.10
github.com/prometheus/client_golang v1.23.2
github.com/shirou/gopsutil/v3 v3.24.5
gopkg.in/yaml.v2 v2.4.0
)
require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/common v0.42.0 // indirect
github.com/prometheus/procfs v0.10.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
github.com/yusufpapurcu/wmi v1.2.3 // indirect
golang.org/x/sys v0.13.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/sys v0.35.0 // indirect
google.golang.org/protobuf v1.36.8 // indirect
)
+43 -41
View File
@@ -1,70 +1,72 @@
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8=
github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc=
github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4=
github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w=
github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM=
github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc=
github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+PymziUAg=
github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM=
github.com/shirou/gopsutil/v3 v3.23.10 h1:/N42opWlYzegYaVkWejXWJpbzKv2JDy3mrgGzKsh9hM=
github.com/shirou/gopsutil/v3 v3.23.10/go.mod h1:JIE26kpucQi+innVlAUnIEOSBhBUkirr5b44yr55+WE=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU=
github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw=
github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+324 -242
View File
@@ -1,323 +1,286 @@
package main
import (
"encoding/json"
"context"
"flag"
"io/ioutil"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"sync"
"syscall"
"time"
"gopkg.in/yaml.v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/shirou/gopsutil/v3/process"
)
var verbose bool = false
var collectionInterval time.Duration = 0
type Config struct {
Processes []string `json:"processes"`
Processes []string `yaml:"processes"`
}
type Exporter struct {
config Config
cpuUsage *prometheus.GaugeVec
memoryUsage *prometheus.GaugeVec
memoryPercent *prometheus.GaugeVec
uptime *prometheus.GaugeVec
openFiles *prometheus.GaugeVec
threadCount *prometheus.GaugeVec
residentMemory *prometheus.GaugeVec
virtualMemory *prometheus.GaugeVec
readBytes *prometheus.CounterVec
writeBytes *prometheus.CounterVec
metricsCache map[string]prometheus.Metric
lastCollection time.Time
mutex sync.Mutex
config Config
metrics *ProcessMetrics
lastCollection time.Time
mutex sync.Mutex
verbose bool
}
func NewExporter(config Config) *Exporter {
exporter := &Exporter{
type ProcessMetrics struct {
cpuUsage *prometheus.GaugeVec
memoryUsage *prometheus.GaugeVec
memoryPercent *prometheus.GaugeVec
uptime *prometheus.GaugeVec
openFiles *prometheus.GaugeVec
threadCount *prometheus.GaugeVec
residentMemory *prometheus.GaugeVec
virtualMemory *prometheus.GaugeVec
readBytes *prometheus.CounterVec
writeBytes *prometheus.CounterVec
}
func NewExporter(config Config, verbose bool) *Exporter {
return &Exporter{
config: config,
metricsCache: make(map[string]prometheus.Metric),
metrics: newProcessMetrics(),
lastCollection: time.Now(),
verbose: verbose,
}
}
exporter.cpuUsage = prometheus.NewGaugeVec(
func newProcessMetrics() *ProcessMetrics {
return &ProcessMetrics{
cpuUsage: createGaugeVec("process_cpu_usage_percent", "CPU usage percentage of the process"),
memoryUsage: createGaugeVec("process_memory_usage_bytes", "Memory usage in bytes of the process"),
memoryPercent: createGaugeVec("process_memory_percent", "Memory usage percentage of the process"),
uptime: createGaugeVec("process_uptime_seconds", "Uptime of the process in seconds"),
openFiles: createGaugeVec("process_open_files", "Number of open files by the process"),
threadCount: createGaugeVec("process_thread_count", "Number of threads used by the process"),
residentMemory: createGaugeVec("process_resident_memory_bytes", "Resident memory size in bytes"),
virtualMemory: createGaugeVec("process_virtual_memory_bytes", "Virtual memory size in bytes"),
readBytes: createCounterVec("process_read_bytes_total", "Total number of bytes read by the process"),
writeBytes: createCounterVec("process_write_bytes_total", "Total number of bytes written by the process"),
}
}
func createGaugeVec(name, help string) *prometheus.GaugeVec {
return prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "process_cpu_usage_percent",
Help: "CPU usage percentage of the process",
Name: name,
Help: help,
},
[]string{"process", "pid"},
)
}
exporter.memoryUsage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "process_memory_usage_bytes",
Help: "Memory usage in bytes of the process",
},
[]string{"process", "pid"},
)
exporter.memoryPercent = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "process_memory_percent",
Help: "Memory usage percentage of the process",
},
[]string{"process", "pid"},
)
exporter.uptime = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "process_uptime_seconds",
Help: "Uptime of the process in seconds",
},
[]string{"process", "pid"},
)
exporter.openFiles = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "process_open_files",
Help: "Number of open files by the process",
},
[]string{"process", "pid"},
)
exporter.threadCount = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "process_thread_count",
Help: "Number of threads used by the process",
},
[]string{"process", "pid"},
)
exporter.residentMemory = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "process_resident_memory_bytes",
Help: "Resident memory size in bytes",
},
[]string{"process", "pid"},
)
exporter.virtualMemory = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "process_virtual_memory_bytes",
Help: "Virtual memory size in bytes",
},
[]string{"process", "pid"},
)
exporter.readBytes = prometheus.NewCounterVec(
func createCounterVec(name, help string) *prometheus.CounterVec {
return prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "process_read_bytes_total",
Help: "Total number of bytes read by the process",
Name: name,
Help: help,
},
[]string{"process", "pid"},
)
exporter.writeBytes = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "process_write_bytes_total",
Help: "Total number of bytes written by the process",
},
[]string{"process", "pid"},
)
return exporter
}
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
e.cpuUsage.Describe(ch)
e.memoryUsage.Describe(ch)
e.memoryPercent.Describe(ch)
e.uptime.Describe(ch)
e.openFiles.Describe(ch)
e.threadCount.Describe(ch)
e.residentMemory.Describe(ch)
e.virtualMemory.Describe(ch)
e.readBytes.Describe(ch)
e.writeBytes.Describe(ch)
e.metrics.describeAll(ch)
}
func (pm *ProcessMetrics) describeAll(ch chan<- *prometheus.Desc) {
pm.cpuUsage.Describe(ch)
pm.memoryUsage.Describe(ch)
pm.memoryPercent.Describe(ch)
pm.uptime.Describe(ch)
pm.openFiles.Describe(ch)
pm.threadCount.Describe(ch)
pm.residentMemory.Describe(ch)
pm.virtualMemory.Describe(ch)
pm.readBytes.Describe(ch)
pm.writeBytes.Describe(ch)
}
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
if e.verbose {
log.Printf("Serving metrics from cache (last collected: %s)", e.lastCollection.Format("15:04:05"))
}
e.metrics.collectAll(ch)
if e.verbose {
log.Printf("Metrics served successfully")
}
}
func (pm *ProcessMetrics) collectAll(ch chan<- prometheus.Metric) {
pm.cpuUsage.Collect(ch)
pm.memoryUsage.Collect(ch)
pm.memoryPercent.Collect(ch)
pm.uptime.Collect(ch)
pm.openFiles.Collect(ch)
pm.threadCount.Collect(ch)
pm.residentMemory.Collect(ch)
pm.virtualMemory.Collect(ch)
pm.readBytes.Collect(ch)
pm.writeBytes.Collect(ch)
}
func (e *Exporter) collectAndCacheMetrics() {
e.mutex.Lock()
defer e.mutex.Unlock()
if verbose {
if e.verbose {
log.Printf("Collecting metrics for processes: %v", e.config.Processes)
}
e.cpuUsage.Reset()
e.memoryUsage.Reset()
e.memoryPercent.Reset()
e.uptime.Reset()
e.openFiles.Reset()
e.threadCount.Reset()
e.residentMemory.Reset()
e.virtualMemory.Reset()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
done := make(chan struct{})
go func() {
select {
case <-ctx.Done():
log.Printf("Warning: Metric collection timed out after 30 seconds")
return
case <-done:
return
}
}()
e.metrics.resetAll()
procs, err := process.Processes()
if err != nil {
log.Printf("Error getting processes: %v", err)
return
}
processNames := make(map[string]bool)
for _, procName := range e.config.Processes {
procs, err := process.Processes()
processNames[procName] = true
}
foundCounts := make(map[string]int)
for _, proc := range procs {
name, err := proc.Name()
if err != nil {
log.Printf("Error getting processes: %v", err)
continue
}
foundCount := 0
for _, proc := range procs {
name, err := proc.Name()
if err == nil && name == procName {
foundCount++
e.collectProcessMetrics(proc, procName)
if verbose {
log.Printf("Collected metrics for %s (PID: %d)", procName, proc.Pid)
}
if processNames[name] {
foundCounts[name]++
e.collectProcessMetrics(proc, name)
if e.verbose {
log.Printf("Collected metrics for %s (PID: %d)", name, proc.Pid)
}
}
if verbose {
log.Printf("Found %d instances of %s", foundCount, procName)
}
for _, procName := range e.config.Processes {
if e.verbose {
log.Printf("Found %d instances of %s", foundCounts[procName], procName)
}
}
close(done)
e.lastCollection = time.Now()
if verbose {
if e.verbose {
log.Printf("Metrics collection completed and cached")
}
}
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
if verbose {
log.Printf("Serving metrics from cache (last collected: %s)", e.lastCollection.Format("15:04:05"))
}
e.cpuUsage.Collect(ch)
e.memoryUsage.Collect(ch)
e.memoryPercent.Collect(ch)
e.uptime.Collect(ch)
e.openFiles.Collect(ch)
e.threadCount.Collect(ch)
e.residentMemory.Collect(ch)
e.virtualMemory.Collect(ch)
e.readBytes.Collect(ch)
e.writeBytes.Collect(ch)
if verbose {
log.Printf("Metrics served successfully")
}
func (pm *ProcessMetrics) resetAll() {
pm.cpuUsage.Reset()
pm.memoryUsage.Reset()
pm.memoryPercent.Reset()
pm.uptime.Reset()
pm.openFiles.Reset()
pm.threadCount.Reset()
pm.residentMemory.Reset()
pm.virtualMemory.Reset()
}
func (e *Exporter) collectProcessMetrics(proc *process.Process, procName string) {
pid := strconv.Itoa(int(proc.Pid))
cpuPercent, err := proc.CPUPercent()
if err == nil {
e.cpuUsage.WithLabelValues(procName, pid).Set(cpuPercent)
if cpuPercent, err := proc.CPUPercent(); err == nil {
e.metrics.cpuUsage.WithLabelValues(procName, pid).Set(cpuPercent)
if e.verbose {
log.Printf(" CPU%%: %.2f%%", cpuPercent)
}
} else if e.verbose {
log.Printf(" CPU%%: error - %v", err)
}
memInfo, err := proc.MemoryInfo()
if err == nil {
e.memoryUsage.WithLabelValues(procName, pid).Set(float64(memInfo.RSS))
e.residentMemory.WithLabelValues(procName, pid).Set(float64(memInfo.RSS))
e.virtualMemory.WithLabelValues(procName, pid).Set(float64(memInfo.VMS))
if memInfo, err := proc.MemoryInfo(); err == nil {
e.metrics.memoryUsage.WithLabelValues(procName, pid).Set(float64(memInfo.RSS))
e.metrics.residentMemory.WithLabelValues(procName, pid).Set(float64(memInfo.RSS))
e.metrics.virtualMemory.WithLabelValues(procName, pid).Set(float64(memInfo.VMS))
if e.verbose {
log.Printf(" Memory: RSS=%d bytes, VMS=%d bytes", memInfo.RSS, memInfo.VMS)
}
} else if e.verbose {
log.Printf(" Memory: error - %v", err)
}
memPercent, err := proc.MemoryPercent()
if err == nil {
e.memoryPercent.WithLabelValues(procName, pid).Set(float64(memPercent))
if memPercent, err := proc.MemoryPercent(); err == nil {
e.metrics.memoryPercent.WithLabelValues(procName, pid).Set(float64(memPercent))
if e.verbose {
log.Printf(" Memory%%: %.2f%%", memPercent)
}
} else if e.verbose {
log.Printf(" Memory%%: error - %v", err)
}
createTime, err := proc.CreateTime()
if err == nil {
if createTime, err := proc.CreateTime(); err == nil {
uptimeSeconds := float64(time.Now().Unix() - int64(createTime/1000))
e.uptime.WithLabelValues(procName, pid).Set(uptimeSeconds)
e.metrics.uptime.WithLabelValues(procName, pid).Set(uptimeSeconds)
if e.verbose {
log.Printf(" Uptime: %.0f seconds", uptimeSeconds)
}
} else if e.verbose {
log.Printf(" Uptime: error - %v", err)
}
openFiles, err := proc.NumFDs()
if err == nil {
e.openFiles.WithLabelValues(procName, pid).Set(float64(openFiles))
if openFiles, err := proc.NumFDs(); err == nil {
e.metrics.openFiles.WithLabelValues(procName, pid).Set(float64(openFiles))
if e.verbose {
log.Printf(" Open files: %d", openFiles)
}
} else if e.verbose {
log.Printf(" Open files: error - %v", err)
}
threadCount, err := proc.NumThreads()
if err == nil {
e.threadCount.WithLabelValues(procName, pid).Set(float64(threadCount))
if threadCount, err := proc.NumThreads(); err == nil {
e.metrics.threadCount.WithLabelValues(procName, pid).Set(float64(threadCount))
if e.verbose {
log.Printf(" Threads: %d", threadCount)
}
} else if e.verbose {
log.Printf(" Threads: error - %v", err)
}
ioCounters, err := proc.IOCounters()
if err == nil {
e.readBytes.WithLabelValues(procName, pid).Add(float64(ioCounters.ReadBytes))
e.writeBytes.WithLabelValues(procName, pid).Add(float64(ioCounters.WriteBytes))
if ioCounters, err := proc.IOCounters(); err == nil {
e.metrics.readBytes.WithLabelValues(procName, pid).Add(float64(ioCounters.ReadBytes))
e.metrics.writeBytes.WithLabelValues(procName, pid).Add(float64(ioCounters.WriteBytes))
if e.verbose {
log.Printf(" I/O: Read=%d bytes, Write=%d bytes", ioCounters.ReadBytes, ioCounters.WriteBytes)
}
} else if e.verbose {
log.Printf(" I/O: error - %v", err)
}
}
func main() {
configFile := flag.String("c", "config.json", "Path to configuration file")
listenAddr := flag.String("l", ":9064", "Address to listen on")
verboseFlag := flag.Bool("v", false, "Enable verbose logging")
interval := flag.Duration("i", 10*time.Second, "Interval between metrics collections (e.g., 5s, 1m). 0 means collect on demand only.")
flag.Parse()
verbose = *verboseFlag
collectionInterval = *interval
config, err := readConfig(*configFile)
if err != nil {
log.Fatalf("Error reading config: %v", err)
}
// Create a custom registry
reg := prometheus.NewRegistry()
// Create exporter
exporter := NewExporter(config)
// Perform initial metrics collection
exporter.collectAndCacheMetrics()
// Register the exporter as a collector in our custom registry
reg.MustRegister(exporter)
// Set up HTTP server with custom registry
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
// Wrap the default serve mux with logging if verbose mode is enabled
var handler http.Handler = http.DefaultServeMux
if verbose {
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("HTTP Request: %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
http.DefaultServeMux.ServeHTTP(w, r)
})
}
if collectionInterval > 0 {
if verbose {
log.Printf("Starting periodic metrics collection every %s", collectionInterval)
}
go func() {
ticker := time.NewTicker(collectionInterval)
defer ticker.Stop()
for range ticker.C {
exporter.collectAndCacheMetrics()
}
}()
} else {
if verbose {
log.Printf("Metrics collection on demand only (no periodic collection)")
}
}
log.Printf("Starting process exporter on %s", *listenAddr)
if verbose {
log.Printf("Verbose logging enabled")
}
log.Fatal(http.ListenAndServe(*listenAddr, handler))
}
func readConfig(filename string) (Config, error) {
func readConfig(filename string, verbose bool) (Config, error) {
var config Config
paths := []string{
@@ -330,8 +293,11 @@ func readConfig(filename string) (Config, error) {
var err error
for _, path := range paths {
configData, err = ioutil.ReadFile(path)
configData, err = os.ReadFile(path)
if err == nil {
if verbose {
log.Printf("Using config file from: %s", path)
}
break
}
if !os.IsNotExist(err) {
@@ -343,10 +309,126 @@ func readConfig(filename string) (Config, error) {
return config, os.ErrNotExist
}
err = json.Unmarshal(configData, &config)
var yamlConfig struct {
Processes []string `yaml:"processes"`
}
err = yaml.Unmarshal(configData, &yamlConfig)
if err != nil {
return config, err
return config, fmt.Errorf("failed to parse YAML configuration: %v", err)
}
config.Processes = yamlConfig.Processes
if verbose {
log.Printf("Parsed YAML configuration")
}
if len(config.Processes) == 0 {
return config, fmt.Errorf("config validation failed: no processes specified in config")
}
seen := make(map[string]bool)
uniqueProcesses := []string{}
for _, proc := range config.Processes {
if !seen[proc] {
seen[proc] = true
uniqueProcesses = append(uniqueProcesses, proc)
}
}
config.Processes = uniqueProcesses
if verbose {
log.Printf("Loaded config with %d unique processes: %v", len(config.Processes), config.Processes)
}
return config, nil
}
func setupHTTPServer(listenAddr string, handler http.Handler, verbose bool) *http.Server {
return &http.Server{
Addr: listenAddr,
Handler: handler,
}
}
func createLoggingHandler(verbose bool) http.Handler {
if !verbose {
return http.DefaultServeMux
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("HTTP Request: %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
http.DefaultServeMux.ServeHTTP(w, r)
})
}
func main() {
configFile := flag.String("c", "config.yml", "Path to configuration file")
listenAddr := flag.String("l", ":9064", "Address to listen on")
verbose := flag.Bool("v", false, "Enable verbose logging")
interval := flag.Duration("i", 10*time.Second, "Interval between metrics collections (e.g., 5s, 1m). 0 means collect on demand only.")
flag.Parse()
config, err := readConfig(*configFile, *verbose)
if err != nil {
log.Fatalf("Error reading config: %v", err)
}
reg := prometheus.NewRegistry()
exporter := NewExporter(config, *verbose)
exporter.collectAndCacheMetrics()
reg.MustRegister(exporter)
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
handler := createLoggingHandler(*verbose)
if *interval > 0 {
if *verbose {
log.Printf("Starting periodic metrics collection every %s", *interval)
}
go func() {
ticker := time.NewTicker(*interval)
defer ticker.Stop()
for range ticker.C {
exporter.collectAndCacheMetrics()
}
}()
} else {
if *verbose {
log.Printf("Metrics collection on demand only (no periodic collection)")
}
}
server := setupHTTPServer(*listenAddr, handler, *verbose)
shutdownChan := make(chan os.Signal, 1)
signal.Notify(shutdownChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
log.Printf("Starting process exporter on %s", *listenAddr)
if *verbose {
log.Printf("Verbose logging enabled")
}
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server error: %v", err)
}
}()
<-shutdownChan
log.Printf("Shutdown signal received, shutting down gracefully...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Printf("Server shutdown error: %v", err)
}
log.Printf("Server stopped gracefully")
}