prometheus-fail2ban-exporter/db/db.go
Hector 0b40e5de82 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.
2021-02-06 11:50:13 +00:00

51 lines
828 B
Go

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)
}
}