You've already forked prometheus-fail2ban-exporter
feat: connect to fail2ban db and extract total bad ips
Add dependencies on `sqlite` to allow connecting to the fail2ban database. Add a new `db` module to handle all the database connections and data queries used to generate metrics. Export a new metric for the total number of bad IPs stored in the fail2ban database.
This commit is contained in:
50
db/db.go
Normal file
50
db/db.go
Normal file
@ -0,0 +1,50 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const queryCountTotalBadIps = "SELECT COUNT(1) FROM bips"
|
||||
|
||||
type Fail2BanDB struct {
|
||||
DatabasePath string
|
||||
sqliteDB *sql.DB
|
||||
}
|
||||
|
||||
func MustConnectToDb(databasePath string) *Fail2BanDB {
|
||||
db, err := sql.Open("sqlite3", databasePath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return &Fail2BanDB{
|
||||
DatabasePath: databasePath,
|
||||
sqliteDB: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (db *Fail2BanDB) CountTotalBadIps() (int, error) {
|
||||
stmt, err := db.sqliteDB.Prepare(queryCountTotalBadIps)
|
||||
defer db.mustCloseStatement(stmt)
|
||||
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
result := ""
|
||||
err = stmt.QueryRow().Scan(&result)
|
||||
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
return strconv.Atoi(result)
|
||||
}
|
||||
|
||||
func (db *Fail2BanDB) mustCloseStatement(stmt *sql.Stmt) {
|
||||
err := stmt.Close()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user