0b40e5de82
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.
51 lines
828 B
Go
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)
|
|
}
|
|
}
|