use more specific methods to retrieve record fields

This commit is contained in:
Henry Dollman
2024-07-31 16:52:26 -04:00
parent de7e07963d
commit 4dd201de0d
3 changed files with 23 additions and 28 deletions

View File

@@ -1,19 +1,17 @@
package main
import (
"encoding/json"
"fmt"
"net/mail"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/types"
)
func handleSystemAlerts(newStatus string, newRecord *models.Record, oldRecord *models.Record) {
alertRecords, err := app.Dao().FindRecordsByExpr("alerts",
dbx.NewExp("system = {:system}", dbx.Params{"system": oldRecord.Get("id")}),
dbx.NewExp("system = {:system}", dbx.Params{"system": oldRecord.GetId()}),
)
if err != nil || len(alertRecords) == 0 {
// log.Println("no alerts found for system")
@@ -22,7 +20,7 @@ func handleSystemAlerts(newStatus string, newRecord *models.Record, oldRecord *m
// log.Println("found alerts", len(alertRecords))
var systemInfo *SystemInfo
for _, alertRecord := range alertRecords {
name := alertRecord.Get("name").(string)
name := alertRecord.GetString("name")
switch name {
case "Status":
handleStatusAlerts(newStatus, oldRecord, alertRecord)
@@ -46,24 +44,24 @@ func handleSystemAlerts(newStatus string, newRecord *models.Record, oldRecord *m
func getSystemInfo(record *models.Record) *SystemInfo {
var SystemInfo SystemInfo
json.Unmarshal([]byte(record.Get("info").(types.JsonRaw)), &SystemInfo)
record.UnmarshalJSONField("info", &SystemInfo)
return &SystemInfo
}
func handleSlidingValueAlert(newRecord *models.Record, alertRecord *models.Record, name string, curValue float64) {
triggered := alertRecord.Get("triggered").(bool)
threshold := alertRecord.Get("value").(float64)
triggered := alertRecord.GetBool("triggered")
threshold := alertRecord.GetFloat("value")
// fmt.Println(name, curValue, "threshold", threshold, "triggered", triggered)
var subject string
var body string
if !triggered && curValue > threshold {
alertRecord.Set("triggered", true)
systemName := newRecord.Get("name").(string)
systemName := newRecord.GetString("name")
subject = fmt.Sprintf("%s usage threshold exceeded on %s", name, systemName)
body = fmt.Sprintf("%s usage on %s is %.1f%%.\n\n- Beszel", name, systemName, curValue)
body = fmt.Sprintf("%s usage on %s is %.1f%%.\n\n%s\n\n- Beszel", name, systemName, curValue, app.Settings().Meta.AppUrl+"/system/"+systemName)
} else if triggered && curValue <= threshold {
alertRecord.Set("triggered", false)
systemName := newRecord.Get("name").(string)
systemName := newRecord.GetString("name")
subject = fmt.Sprintf("%s usage returned below threshold on %s", name, systemName)
body = fmt.Sprintf("%s usage on %s is below threshold at %.1f%%.\n\n%s\n\n- Beszel", name, systemName, curValue, app.Settings().Meta.AppUrl+"/system/"+systemName)
} else {
@@ -81,7 +79,7 @@ func handleSlidingValueAlert(newRecord *models.Record, alertRecord *models.Recor
}
if user := alertRecord.ExpandedOne("user"); user != nil {
sendAlert(EmailData{
to: user.Get("email").(string),
to: user.GetString("email"),
subj: subject,
body: body,
})
@@ -92,11 +90,11 @@ func handleStatusAlerts(newStatus string, oldRecord *models.Record, alertRecord
var alertStatus string
switch newStatus {
case "up":
if oldRecord.Get("status") == "down" {
if oldRecord.GetString("status") == "down" {
alertStatus = "up"
}
case "down":
if oldRecord.Get("status") == "up" {
if oldRecord.GetString("status") == "up" {
alertStatus = "down"
}
}
@@ -116,9 +114,9 @@ func handleStatusAlerts(newStatus string, oldRecord *models.Record, alertRecord
emoji = "\u2705"
}
// send alert
systemName := oldRecord.Get("name").(string)
systemName := oldRecord.GetString("name")
sendAlert(EmailData{
to: user.Get("email").(string),
to: user.GetString("email"),
subj: fmt.Sprintf("Connection to %s is %s %v", systemName, alertStatus, emoji),
body: fmt.Sprintf("Connection to %s is %s\n\n- Beszel", systemName, alertStatus),
})

View File

@@ -26,7 +26,6 @@ import (
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/plugins/migratecmd"
"github.com/pocketbase/pocketbase/tools/cron"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
)
@@ -155,7 +154,7 @@ func main() {
// user creation - set default role to user if unset
app.OnModelBeforeCreate("users").Add(func(e *core.ModelEvent) error {
user := e.Model.(*models.Record)
if user.Get("role") == "" {
if user.GetString("role") == "" {
user.Set("role", "user")
}
return nil
@@ -180,7 +179,7 @@ func main() {
app.OnModelAfterUpdate("systems").Add(func(e *core.ModelEvent) error {
newRecord := e.Model.(*models.Record)
oldRecord := newRecord.OriginalCopy()
newStatus := newRecord.Get("status").(string)
newStatus := newRecord.GetString("status")
// if server is disconnected and connection exists, remove it
if newStatus == "down" || newStatus == "paused" {
@@ -242,7 +241,7 @@ func updateSystems() {
fiftySecondsAgo := time.Now().UTC().Add(-50 * time.Second)
batchSize := len(records)/4 + 1
for i := 0; i < batchSize; i++ {
if records[i].Get("updated").(types.DateTime).Time().After(fiftySecondsAgo) {
if records[i].GetDateTime("updated").Time().After(fiftySecondsAgo) {
break
}
// log.Println("updating", records[i].Get(("name")))
@@ -258,8 +257,8 @@ func updateSystem(record *models.Record) {
} else {
// create server connection struct
server = &Server{
Host: record.Get("host").(string),
Port: record.Get("port").(string),
Host: record.GetString("host"),
Port: record.GetString("port"),
}
client, err := getServerConnection(server)
if err != nil {
@@ -321,7 +320,7 @@ func updateServerStatus(record *models.Record, status string) {
// if status == "down" || status == "paused" {
// deleteServerConnection(record)
// }
if record.Get("status") != status {
if record.GetString("status") != status {
record.Set("status", status)
if err := app.Dao().SaveRecord(record); err != nil {
app.Logger().Error("Failed to update record: ", "err", err.Error())

View File

@@ -1,7 +1,6 @@
package main
import (
"encoding/json"
"fmt"
"math"
"reflect"
@@ -10,12 +9,11 @@ import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/types"
)
func createLongerRecords(collectionName string, shorterRecord *models.Record) {
shorterRecordType := shorterRecord.Get("type").(string)
systemId := shorterRecord.Get("system").(string)
shorterRecordType := shorterRecord.GetString("type")
systemId := shorterRecord.GetString("system")
// fmt.Println("create longer records", "recordType", shorterRecordType, "systemId", systemId)
var longerRecordType string
var timeAgo time.Duration
@@ -92,7 +90,7 @@ func averageSystemStats(records []*models.Record) SystemStats {
for _, record := range records {
var stats SystemStats
json.Unmarshal([]byte(record.Get("stats").(types.JsonRaw)), &stats)
record.UnmarshalJSONField("stats", &stats)
statValue := reflect.ValueOf(stats)
for i := 0; i < statValue.NumField(); i++ {
field := sum.Field(i)
@@ -114,7 +112,7 @@ func averageContainerStats(records []*models.Record) (stats []ContainerStats) {
count := float64(len(records))
for _, record := range records {
var stats []ContainerStats
json.Unmarshal([]byte(record.Get("stats").(types.JsonRaw)), &stats)
record.UnmarshalJSONField("stats", &stats)
for _, stat := range stats {
if _, ok := sums[stat.Name]; !ok {
sums[stat.Name] = &ContainerStats{Name: stat.Name, Cpu: 0, Mem: 0}