Skip to content

Instantly share code, notes, and snippets.

@UlricQin
Last active September 5, 2023 10:23
Show Gist options
  • Save UlricQin/d333ff9bbd538131d054e4153fbdb5e1 to your computer and use it in GitHub Desktop.
Save UlricQin/d333ff9bbd538131d054e4153fbdb5e1 to your computer and use it in GitHub Desktop.
gorm demo
package main
import (
"encoding/json"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type EnabledTime struct {
Days []int64 `json:"days"`
Stime string `json:"stime"`
Etime string `json:"etime"`
}
type Promql struct {
Name string `json:"name"`
Query string `json:"query"`
}
type Condition struct {
Oper string `json:"oper"`
Args []string `json:"args"`
}
type CheckThreshold struct {
Enabled bool `json:"enabled"`
AlertingCheckTimes int `json:"alerting_check_times"`
RecoveryCheckTimes int `json:"recovery_check_times"`
PushRecoveryEvent bool `json:"push_recovery_event"`
Critical []Condition `json:"critical"`
Warning []Condition `json:"warning"`
Info []Condition `json:"info"`
}
type CheckData struct {
Enabled bool `json:"enabled"`
AlertingCheckTimes int `json:"alerting_check_times"`
RecoveryCheckTimes int `json:"recovery_check_times"`
PushRecoveryEvent bool `json:"push_recovery_event"`
Severity string `json:"severity"`
Mode string `json:"mode"`
}
type PrometheusConfig struct {
Queries []Promql `json:"queries"`
ResultExpression string `json:"result_expression"`
CheckThreshold *CheckThreshold `json:"check_threshold,omitempty"`
CheckData *CheckData `json:"check_data,omitempty"`
}
type AlertRule struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt int64 `json:"created_at" gorm:"not null"`
UpdatedAt int64 `json:"updated_at" gorm:"index;not null"`
Name string `json:"name" gorm:"size:128;not null"`
DatasourceType string `json:"datasource_type" gorm:"size:128;not null"`
DatasourceSelected []string `json:"datasource_selected" gorm:"serializer:json;size:1024"`
Labels map[string]string `json:"labels" gorm:"serializer:json;size:1024"`
Annotations map[string]string `json:"annotations" gorm:"serializer:json;size:2048"`
Description string `json:"description" gorm:"type:text"`
WorkspaceIDs []int64 `json:"workspace_ids" gorm:"serializer:json;size:1024"`
RepeatIntervalSeconds int `json:"repeat_interval_seconds" gorm:"not null"`
RepeatTotal int `json:"repeat_total" gorm:"not null"`
EnabledTimes []EnabledTime `json:"enabled_times" gorm:"serializer:json;size:1024"`
Prometheus *PrometheusConfig `json:"prometheus" gorm:"serializer:json;type:text;not null"`
}
var s = `
{
"name": "CPU High",
"datasource_type": "prometheus",
"datasource_selected": ["vm*", "prom*"],
"labels": {
"dept": "cloud",
"region": "beijing"
},
"annotations": {
"RunbookURL": "http://a.com",
"DashboardURL": "http://b.com"
},
"description": "this is markdown",
"workspace_ids": [1, 3],
"repeat_interval_seconds": 3600,
"repeat_total": 3,
"enabled_times": [
{
"days": [1, 2, 3, 4, 5],
"stime": "00:00",
"etime": "00:00"
},
{
"days": [6, 7],
"stime": "08:00",
"etime": "20:00"
}
],
"prometheus": {
"queries": [
{
"name": "cpu_usage_user",
"query": "last_over_time(cpu_usage_user{cpu=\"cpu-total\"}[2m])"
},
{
"name": "cpu_usage_sys",
"query": "last_over_time(cpu_usage_sys{cpu=\"cpu-total\"}[2m])"
}
],
"result_expression": "$cpu_usage_user + $cpu_usage_sys",
"check_threshold": {
"enabled": true,
"alerting_check_times": 2,
"recovery_check_times": 1,
"push_recovery_event": true,
"critical": [
{
"oper": ">=",
"args": ["85.5"]
},
{
"oper": "between",
"args": ["-1000k", "1000k"]
}
],
"warning": [],
"info": []
}
}
}
`
// "check_data": {
// "enabled": true,
// "alerting_check_times": 2,
// "recovery_check_times": 1,
// "push_recovery_event": true,
// "severity": "critical | warning | info",
// "mode": "nodata | anydata"
// }
func main() {
var obj AlertRule
err := json.Unmarshal([]byte(s), &obj)
if err != nil {
fmt.Println("failed to unmarshal json:", err)
return
}
dsn := "root:1234@tcp(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("failed to open db:", err)
return
}
// Auto Migrate
db.AutoMigrate(&AlertRule{})
err = db.Create(&obj).Error
if err != nil {
fmt.Println("failed to create:", err)
return
}
obj.ID = 0
err = db.First(&obj, "id = 1").Error
if err != nil {
fmt.Println("failed to find:", err)
return
}
bs, err := json.Marshal(obj)
if err != nil {
fmt.Println("failed to marshal json:", err)
return
}
fmt.Println(string(bs))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment