diff --git a/internal/activities/healthcheck.go b/internal/activities/monitor.go similarity index 63% rename from internal/activities/healthcheck.go rename to internal/activities/monitor.go index d4c3ce6..4c64769 100644 --- a/internal/activities/healthcheck.go +++ b/internal/activities/monitor.go @@ -16,12 +16,12 @@ type HealtcheckParam struct { Script string } -type HealthcheckResult struct { +type MonitorResult struct { Success bool Note string } -func (a *Activities) Healthcheck(ctx context.Context, param HealtcheckParam) (*HealthcheckResult, error) { +func (a *Activities) Monitor(ctx context.Context, param HealtcheckParam) (*MonitorResult, error) { execution := k6.NewExecution(slog.Default(), param.Script) result, err := execution.Run(ctx) @@ -29,7 +29,7 @@ func (a *Activities) Healthcheck(ctx context.Context, param HealtcheckParam) (*H return nil, err } - return &HealthcheckResult{Success: result.Success, Note: result.Note}, nil + return &MonitorResult{Success: result.Success, Note: result.Note}, nil } type HealtcheckAddToHistoryParam struct { @@ -38,13 +38,13 @@ type HealtcheckAddToHistoryParam struct { Note string } -type HealthcheckAddToHistoryResult struct { +type MonitorAddToHistoryResult struct { } -func (a *Activities) HealthcheckAddToHistory(ctx context.Context, param HealtcheckAddToHistoryParam) (*HealthcheckAddToHistoryResult, error) { - url := fmt.Sprintf("%s/api/v1/healthchecks/%s/history", a.config.ApiUrl, param.Slug) +func (a *Activities) MonitorAddToHistory(ctx context.Context, param HealtcheckAddToHistoryParam) (*MonitorAddToHistoryResult, error) { + url := fmt.Sprintf("%s/api/v1/monitors/%s/history", a.config.ApiUrl, param.Slug) - body := api.ApiV1HealthchecksHistoryPOSTBody{ + body := api.ApiV1MonitorsHistoryPOSTBody{ Status: param.Status, Note: param.Note, } @@ -69,5 +69,5 @@ func (a *Activities) HealthcheckAddToHistory(ctx context.Context, param Healtche return nil, fmt.Errorf("unexpected status code: %d", response.StatusCode) } - return &HealthcheckAddToHistoryResult{}, nil + return &MonitorAddToHistoryResult{}, nil } diff --git a/internal/database.go b/internal/database.go index 15f15b3..23cb656 100644 --- a/internal/database.go +++ b/internal/database.go @@ -16,8 +16,8 @@ func ConnectToDatabase(path string) (*gorm.DB, *query.Query, error) { err = db.AutoMigrate( models.Worker{}, - models.Healthcheck{}, - models.HealthcheckHistory{}, + models.Monitor{}, + models.MonitorHistory{}, models.Cronjob{}, models.CronjobHistory{}, models.OAuth2State{}, diff --git a/internal/handlers/api.go b/internal/handlers/api.go index 709f732..51844e0 100644 --- a/internal/handlers/api.go +++ b/internal/handlers/api.go @@ -42,24 +42,24 @@ func (h *BaseHandler) ApiV1WorkersConnectGET(c echo.Context) error { // TODO: Can we instead get this from the Workflow outcome? // // To somehow listen for the outcomes and then store them automatically. -func (h *BaseHandler) ApiV1HealthchecksHistoryPOST(c echo.Context) error { +func (h *BaseHandler) ApiV1MonitorsHistoryPOST(c echo.Context) error { ctx := context.Background() slug := c.Param("slug") - var body api.ApiV1HealthchecksHistoryPOSTBody + var body api.ApiV1MonitorsHistoryPOSTBody err := (&echo.DefaultBinder{}).BindBody(c, &body) if err != nil { return err } - healthcheck, err := services.GetHealthcheck(ctx, h.query, slug) + monitor, err := services.GetMonitor(ctx, h.query, slug) if err != nil { return err } - err = h.query.Healthcheck.History.Model(healthcheck).Append( - &models.HealthcheckHistory{ + err = h.query.Monitor.History.Model(monitor).Append( + &models.MonitorHistory{ Status: body.Status, Note: body.Note, }) diff --git a/internal/handlers/index.go b/internal/handlers/index.go index e739406..c4d707a 100644 --- a/internal/handlers/index.go +++ b/internal/handlers/index.go @@ -14,7 +14,7 @@ import ( type IndexData struct { *components.Base HealthChecks []*HealthCheck - HealthchecksLength int + MonitorsLength int TimeRange string Status string } @@ -39,7 +39,7 @@ func getHour(date time.Time) string { return date.Format("2006-01-02T15:04") } -func getDailyHistory(history []models.HealthcheckHistory) *History { +func getDailyHistory(history []models.MonitorHistory) *History { numDays := 90 historyDailyMap := map[string]string{} numOfSuccess := 0 @@ -47,7 +47,7 @@ func getDailyHistory(history []models.HealthcheckHistory) *History { for i := 0; i < numDays; i++ { day := getDay(time.Now().AddDate(0, 0, -i).Truncate(time.Hour * 24)) - historyDailyMap[day] = models.HealthcheckUnknown + historyDailyMap[day] = models.MonitorUnknown } for _, _history := range history { @@ -59,12 +59,12 @@ func getDailyHistory(history []models.HealthcheckHistory) *History { } numTotal++ - if _history.Status == models.HealthcheckSuccess { + if _history.Status == models.MonitorSuccess { numOfSuccess++ } // skip if day is already set to failure - if historyDailyMap[day] == models.HealthcheckFailure { + if historyDailyMap[day] == models.MonitorFailure { continue } @@ -88,7 +88,7 @@ func getDailyHistory(history []models.HealthcheckHistory) *History { } } -func getHourlyHistory(history []models.HealthcheckHistory) *History { +func getHourlyHistory(history []models.MonitorHistory) *History { numHours := 48 historyHourlyMap := map[string]string{} numOfSuccess := 0 @@ -96,7 +96,7 @@ func getHourlyHistory(history []models.HealthcheckHistory) *History { for i := 0; i < numHours; i++ { hour := getHour(time.Now().Add(time.Hour * time.Duration(-i)).Truncate(time.Hour)) - historyHourlyMap[hour] = models.HealthcheckUnknown + historyHourlyMap[hour] = models.MonitorUnknown } for _, _history := range history { @@ -108,12 +108,12 @@ func getHourlyHistory(history []models.HealthcheckHistory) *History { } numTotal++ - if _history.Status == models.HealthcheckSuccess { + if _history.Status == models.MonitorSuccess { numOfSuccess++ } // skip if day is already set to failure - if historyHourlyMap[hour] == models.HealthcheckFailure { + if historyHourlyMap[hour] == models.MonitorFailure { continue } @@ -139,7 +139,7 @@ func getHourlyHistory(history []models.HealthcheckHistory) *History { func (h *BaseHandler) Index(c echo.Context) error { ctx := context.Background() - healthchecks, err := services.GetHealthchecks(ctx, h.query) + monitors, err := services.GetMonitors(ctx, h.query) if err != nil { return err } @@ -151,18 +151,18 @@ func (h *BaseHandler) Index(c echo.Context) error { overallStatus := "SUCCESS" - healthchecksWithHistory := make([]*HealthCheck, len(healthchecks)) - for i, healthcheck := range healthchecks { - historyDaily := getDailyHistory(healthcheck.History) - historyHourly := getHourlyHistory(healthcheck.History) + monitorsWithHistory := make([]*HealthCheck, len(monitors)) + for i, monitor := range monitors { + historyDaily := getDailyHistory(monitor.History) + historyHourly := getHourlyHistory(monitor.History) status := historyDaily.History[89] - if status != models.HealthcheckSuccess { + if status != models.MonitorSuccess { overallStatus = status } - healthchecksWithHistory[i] = &HealthCheck{ - Name: healthcheck.Name, + monitorsWithHistory[i] = &HealthCheck{ + Name: monitor.Name, Status: status, HistoryDaily: historyDaily, HistoryHourly: historyHourly, @@ -174,8 +174,8 @@ func (h *BaseHandler) Index(c echo.Context) error { NavbarActive: GetPageByTitle(Pages, "Status"), Navbar: Pages, }, - HealthChecks: healthchecksWithHistory, - HealthchecksLength: len(healthchecks), + HealthChecks: monitorsWithHistory, + MonitorsLength: len(monitors), TimeRange: timeRange, Status: overallStatus, }) diff --git a/internal/handlers/settings.go b/internal/handlers/settings.go index abf7aa3..d818a3b 100644 --- a/internal/handlers/settings.go +++ b/internal/handlers/settings.go @@ -30,9 +30,8 @@ func NewSettings(user *AuthenticatedUser, page *components.Page, breadCrumbs []* var SettingsPages = []*components.Page{ {Path: "/settings", Title: "Overview", Breadcrumb: "Overview"}, - {Path: "/settings/healthchecks", Title: "Healthchecks", Breadcrumb: "Healthchecks"}, - {Path: "/settings/healthchecks/create", Title: "Healthchecks Create", Breadcrumb: "Create"}, - {Path: "/settings/cronjobs", Title: "Cronjobs", Breadcrumb: "Cronjobs"}, + {Path: "/settings/monitors", Title: "Monitors", Breadcrumb: "Monitors"}, + {Path: "/settings/monitors/create", Title: "Monitors Create", Breadcrumb: "Create"}, {Path: "/settings/workers", Title: "Workers", Breadcrumb: "Workers"}, {Path: "/settings/workers/create", Title: "Workers Create", Breadcrumb: "Create"}, {Path: "/settings/notifications", Title: "Notifications", Breadcrumb: "Notifications"}, @@ -42,8 +41,7 @@ var SettingsPages = []*components.Page{ var SettingsNavbar = []*components.Page{ GetPageByTitle(SettingsPages, "Overview"), - GetPageByTitle(SettingsPages, "Healthchecks"), - GetPageByTitle(SettingsPages, "Cronjobs"), + GetPageByTitle(SettingsPages, "Monitors"), GetPageByTitle(SettingsPages, "Workers"), GetPageByTitle(SettingsPages, "Notifications"), GetPageByTitle(SettingsPages, "Temporal"), diff --git a/internal/handlers/settingshealthchecks.go b/internal/handlers/settingshealthchecks.go deleted file mode 100644 index 9f5a85b..0000000 --- a/internal/handlers/settingshealthchecks.go +++ /dev/null @@ -1,157 +0,0 @@ -package handlers - -import ( - "context" - "fmt" - "net/http" - "strings" - - "code.tjo.space/mentos1386/zdravko/internal/models" - "code.tjo.space/mentos1386/zdravko/internal/services" - "code.tjo.space/mentos1386/zdravko/web/templates/components" - "github.com/go-playground/validator/v10" - "github.com/gosimple/slug" - "github.com/labstack/echo/v4" -) - -type SettingsHealthchecks struct { - *Settings - Healthchecks []*models.Healthcheck - HealthchecksLength int -} - -type SettingsHealthcheck struct { - *Settings - Healthcheck *models.Healthcheck -} - -func (h *BaseHandler) SettingsHealthchecksGET(c echo.Context) error { - cc := c.(AuthenticatedContext) - - healthchecks, err := h.query.Healthcheck.WithContext(context.Background()).Find() - if err != nil { - return err - } - - return c.Render(http.StatusOK, "settings_healthchecks.tmpl", &SettingsHealthchecks{ - Settings: NewSettings( - cc.Principal.User, - GetPageByTitle(SettingsPages, "Healthchecks"), - []*components.Page{GetPageByTitle(SettingsPages, "Healthchecks")}, - ), - Healthchecks: healthchecks, - HealthchecksLength: len(healthchecks), - }) -} - -func (h *BaseHandler) SettingsHealthchecksDescribeGET(c echo.Context) error { - cc := c.(AuthenticatedContext) - - slug := c.Param("slug") - - healthcheck, err := services.GetHealthcheck(context.Background(), h.query, slug) - if err != nil { - return err - } - - return c.Render(http.StatusOK, "settings_healthchecks_describe.tmpl", &SettingsHealthcheck{ - Settings: NewSettings( - cc.Principal.User, - GetPageByTitle(SettingsPages, "Healthchecks"), - []*components.Page{ - GetPageByTitle(SettingsPages, "Healthchecks"), - { - Path: fmt.Sprintf("/settings/healthchecks/%s", slug), - Title: "Describe", - Breadcrumb: healthcheck.Name, - }, - }), - Healthcheck: healthcheck, - }) -} - -func (h *BaseHandler) SettingsHealthchecksDescribePOST(c echo.Context) error { - ctx := context.Background() - - slug := c.Param("slug") - - healthcheck, err := services.GetHealthcheck(ctx, h.query, slug) - if err != nil { - return err - } - - update := &models.Healthcheck{ - Slug: healthcheck.Slug, - Name: healthcheck.Name, - Schedule: c.FormValue("schedule"), - WorkerGroups: strings.Split(c.FormValue("workergroups"), " "), - Script: c.FormValue("script"), - } - - err = validator.New(validator.WithRequiredStructEnabled()).Struct(update) - if err != nil { - return err - } - - err = services.UpdateHealthcheck( - ctx, - h.query, - update, - ) - if err != nil { - return err - } - - err = services.CreateOrUpdateHealthcheckSchedule(ctx, h.temporal, healthcheck) - if err != nil { - return err - } - - return c.Redirect(http.StatusSeeOther, fmt.Sprintf("/settings/healthchecks/%s", slug)) -} - -func (h *BaseHandler) SettingsHealthchecksCreateGET(c echo.Context) error { - cc := c.(AuthenticatedContext) - - return c.Render(http.StatusOK, "settings_healthchecks_create.tmpl", NewSettings( - cc.Principal.User, - GetPageByTitle(SettingsPages, "Healthchecks"), - []*components.Page{ - GetPageByTitle(SettingsPages, "Healthchecks"), - GetPageByTitle(SettingsPages, "Healthchecks Create"), - }, - )) -} - -func (h *BaseHandler) SettingsHealthchecksCreatePOST(c echo.Context) error { - ctx := context.Background() - - healthcheckHttp := &models.Healthcheck{ - Name: c.FormValue("name"), - Slug: slug.Make(c.FormValue("name")), - Schedule: c.FormValue("schedule"), - WorkerGroups: strings.Split(c.FormValue("workergroups"), " "), - Script: c.FormValue("script"), - } - - err := validator.New(validator.WithRequiredStructEnabled()).Struct(healthcheckHttp) - if err != nil { - return err - } - - err = services.CreateHealthcheck( - ctx, - h.query, - healthcheckHttp, - ) - if err != nil { - return err - } - - err = services.CreateOrUpdateHealthcheckSchedule(ctx, h.temporal, healthcheckHttp) - if err != nil { - return err - } - - return c.Redirect(http.StatusSeeOther, "/settings/healthchecks") -} diff --git a/internal/handlers/settingsmonitors.go b/internal/handlers/settingsmonitors.go new file mode 100644 index 0000000..0f7ce2d --- /dev/null +++ b/internal/handlers/settingsmonitors.go @@ -0,0 +1,157 @@ +package handlers + +import ( + "context" + "fmt" + "net/http" + "strings" + + "code.tjo.space/mentos1386/zdravko/internal/models" + "code.tjo.space/mentos1386/zdravko/internal/services" + "code.tjo.space/mentos1386/zdravko/web/templates/components" + "github.com/go-playground/validator/v10" + "github.com/gosimple/slug" + "github.com/labstack/echo/v4" +) + +type SettingsMonitors struct { + *Settings + Monitors []*models.Monitor + MonitorsLength int +} + +type SettingsMonitor struct { + *Settings + Monitor *models.Monitor +} + +func (h *BaseHandler) SettingsMonitorsGET(c echo.Context) error { + cc := c.(AuthenticatedContext) + + monitors, err := h.query.Monitor.WithContext(context.Background()).Find() + if err != nil { + return err + } + + return c.Render(http.StatusOK, "settings_monitors.tmpl", &SettingsMonitors{ + Settings: NewSettings( + cc.Principal.User, + GetPageByTitle(SettingsPages, "Monitors"), + []*components.Page{GetPageByTitle(SettingsPages, "Monitors")}, + ), + Monitors: monitors, + MonitorsLength: len(monitors), + }) +} + +func (h *BaseHandler) SettingsMonitorsDescribeGET(c echo.Context) error { + cc := c.(AuthenticatedContext) + + slug := c.Param("slug") + + monitor, err := services.GetMonitor(context.Background(), h.query, slug) + if err != nil { + return err + } + + return c.Render(http.StatusOK, "settings_monitors_describe.tmpl", &SettingsMonitor{ + Settings: NewSettings( + cc.Principal.User, + GetPageByTitle(SettingsPages, "Monitors"), + []*components.Page{ + GetPageByTitle(SettingsPages, "Monitors"), + { + Path: fmt.Sprintf("/settings/monitors/%s", slug), + Title: "Describe", + Breadcrumb: monitor.Name, + }, + }), + Monitor: monitor, + }) +} + +func (h *BaseHandler) SettingsMonitorsDescribePOST(c echo.Context) error { + ctx := context.Background() + + slug := c.Param("slug") + + monitor, err := services.GetMonitor(ctx, h.query, slug) + if err != nil { + return err + } + + update := &models.Monitor{ + Slug: monitor.Slug, + Name: monitor.Name, + Schedule: c.FormValue("schedule"), + WorkerGroups: strings.Split(c.FormValue("workergroups"), " "), + Script: c.FormValue("script"), + } + + err = validator.New(validator.WithRequiredStructEnabled()).Struct(update) + if err != nil { + return err + } + + err = services.UpdateMonitor( + ctx, + h.query, + update, + ) + if err != nil { + return err + } + + err = services.CreateOrUpdateMonitorSchedule(ctx, h.temporal, monitor) + if err != nil { + return err + } + + return c.Redirect(http.StatusSeeOther, fmt.Sprintf("/settings/monitors/%s", slug)) +} + +func (h *BaseHandler) SettingsMonitorsCreateGET(c echo.Context) error { + cc := c.(AuthenticatedContext) + + return c.Render(http.StatusOK, "settings_monitors_create.tmpl", NewSettings( + cc.Principal.User, + GetPageByTitle(SettingsPages, "Monitors"), + []*components.Page{ + GetPageByTitle(SettingsPages, "Monitors"), + GetPageByTitle(SettingsPages, "Monitors Create"), + }, + )) +} + +func (h *BaseHandler) SettingsMonitorsCreatePOST(c echo.Context) error { + ctx := context.Background() + + monitorHttp := &models.Monitor{ + Name: c.FormValue("name"), + Slug: slug.Make(c.FormValue("name")), + Schedule: c.FormValue("schedule"), + WorkerGroups: strings.Split(c.FormValue("workergroups"), " "), + Script: c.FormValue("script"), + } + + err := validator.New(validator.WithRequiredStructEnabled()).Struct(monitorHttp) + if err != nil { + return err + } + + err = services.CreateMonitor( + ctx, + h.query, + monitorHttp, + ) + if err != nil { + return err + } + + err = services.CreateOrUpdateMonitorSchedule(ctx, h.temporal, monitorHttp) + if err != nil { + return err + } + + return c.Redirect(http.StatusSeeOther, "/settings/monitors") +} diff --git a/internal/models/models.go b/internal/models/models.go index 83290ef..2ec2a69 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -21,13 +21,13 @@ type Worker struct { } const ( - HealthcheckSuccess string = "SUCCESS" - HealthcheckFailure string = "FAILURE" - HealthcheckError string = "ERROR" - HealthcheckUnknown string = "UNKNOWN" + MonitorSuccess string = "SUCCESS" + MonitorFailure string = "FAILURE" + MonitorError string = "ERROR" + MonitorUnknown string = "UNKNOWN" ) -type Healthcheck struct { +type Monitor struct { gorm.Model Slug string `gorm:"unique"` Name string `gorm:"unique" validate:"required"` @@ -37,7 +37,7 @@ type Healthcheck struct { Script string `validate:"required"` - History []HealthcheckHistory `gorm:"foreignKey:Healthcheck"` + History []MonitorHistory `gorm:"foreignKey:Monitor"` } type Cronjob struct { @@ -48,9 +48,9 @@ type Cronjob struct { Buffer int } -type HealthcheckHistory struct { +type MonitorHistory struct { gorm.Model - Healthcheck uint + Monitor uint Status string Note string } diff --git a/internal/models/query/gen.go b/internal/models/query/gen.go index 884b246..fd0f308 100644 --- a/internal/models/query/gen.go +++ b/internal/models/query/gen.go @@ -16,59 +16,59 @@ import ( ) var ( - Q = new(Query) - Cronjob *cronjob - CronjobHistory *cronjobHistory - Healthcheck *healthcheck - HealthcheckHistory *healthcheckHistory - OAuth2State *oAuth2State - Worker *worker + Q = new(Query) + Cronjob *cronjob + CronjobHistory *cronjobHistory + Monitor *monitor + MonitorHistory *monitorHistory + OAuth2State *oAuth2State + Worker *worker ) func SetDefault(db *gorm.DB, opts ...gen.DOOption) { *Q = *Use(db, opts...) Cronjob = &Q.Cronjob CronjobHistory = &Q.CronjobHistory - Healthcheck = &Q.Healthcheck - HealthcheckHistory = &Q.HealthcheckHistory + Monitor = &Q.Monitor + MonitorHistory = &Q.MonitorHistory OAuth2State = &Q.OAuth2State Worker = &Q.Worker } func Use(db *gorm.DB, opts ...gen.DOOption) *Query { return &Query{ - db: db, - Cronjob: newCronjob(db, opts...), - CronjobHistory: newCronjobHistory(db, opts...), - Healthcheck: newHealthcheck(db, opts...), - HealthcheckHistory: newHealthcheckHistory(db, opts...), - OAuth2State: newOAuth2State(db, opts...), - Worker: newWorker(db, opts...), + db: db, + Cronjob: newCronjob(db, opts...), + CronjobHistory: newCronjobHistory(db, opts...), + Monitor: newMonitor(db, opts...), + MonitorHistory: newMonitorHistory(db, opts...), + OAuth2State: newOAuth2State(db, opts...), + Worker: newWorker(db, opts...), } } type Query struct { db *gorm.DB - Cronjob cronjob - CronjobHistory cronjobHistory - Healthcheck healthcheck - HealthcheckHistory healthcheckHistory - OAuth2State oAuth2State - Worker worker + Cronjob cronjob + CronjobHistory cronjobHistory + Monitor monitor + MonitorHistory monitorHistory + OAuth2State oAuth2State + Worker worker } func (q *Query) Available() bool { return q.db != nil } func (q *Query) clone(db *gorm.DB) *Query { return &Query{ - db: db, - Cronjob: q.Cronjob.clone(db), - CronjobHistory: q.CronjobHistory.clone(db), - Healthcheck: q.Healthcheck.clone(db), - HealthcheckHistory: q.HealthcheckHistory.clone(db), - OAuth2State: q.OAuth2State.clone(db), - Worker: q.Worker.clone(db), + db: db, + Cronjob: q.Cronjob.clone(db), + CronjobHistory: q.CronjobHistory.clone(db), + Monitor: q.Monitor.clone(db), + MonitorHistory: q.MonitorHistory.clone(db), + OAuth2State: q.OAuth2State.clone(db), + Worker: q.Worker.clone(db), } } @@ -82,33 +82,33 @@ func (q *Query) WriteDB() *Query { func (q *Query) ReplaceDB(db *gorm.DB) *Query { return &Query{ - db: db, - Cronjob: q.Cronjob.replaceDB(db), - CronjobHistory: q.CronjobHistory.replaceDB(db), - Healthcheck: q.Healthcheck.replaceDB(db), - HealthcheckHistory: q.HealthcheckHistory.replaceDB(db), - OAuth2State: q.OAuth2State.replaceDB(db), - Worker: q.Worker.replaceDB(db), + db: db, + Cronjob: q.Cronjob.replaceDB(db), + CronjobHistory: q.CronjobHistory.replaceDB(db), + Monitor: q.Monitor.replaceDB(db), + MonitorHistory: q.MonitorHistory.replaceDB(db), + OAuth2State: q.OAuth2State.replaceDB(db), + Worker: q.Worker.replaceDB(db), } } type queryCtx struct { - Cronjob ICronjobDo - CronjobHistory ICronjobHistoryDo - Healthcheck IHealthcheckDo - HealthcheckHistory IHealthcheckHistoryDo - OAuth2State IOAuth2StateDo - Worker IWorkerDo + Cronjob ICronjobDo + CronjobHistory ICronjobHistoryDo + Monitor IMonitorDo + MonitorHistory IMonitorHistoryDo + OAuth2State IOAuth2StateDo + Worker IWorkerDo } func (q *Query) WithContext(ctx context.Context) *queryCtx { return &queryCtx{ - Cronjob: q.Cronjob.WithContext(ctx), - CronjobHistory: q.CronjobHistory.WithContext(ctx), - Healthcheck: q.Healthcheck.WithContext(ctx), - HealthcheckHistory: q.HealthcheckHistory.WithContext(ctx), - OAuth2State: q.OAuth2State.WithContext(ctx), - Worker: q.Worker.WithContext(ctx), + Cronjob: q.Cronjob.WithContext(ctx), + CronjobHistory: q.CronjobHistory.WithContext(ctx), + Monitor: q.Monitor.WithContext(ctx), + MonitorHistory: q.MonitorHistory.WithContext(ctx), + OAuth2State: q.OAuth2State.WithContext(ctx), + Worker: q.Worker.WithContext(ctx), } } diff --git a/internal/models/query/healthcheck_histories.gen.go b/internal/models/query/healthcheck_histories.gen.go deleted file mode 100644 index 860b805..0000000 --- a/internal/models/query/healthcheck_histories.gen.go +++ /dev/null @@ -1,416 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "code.tjo.space/mentos1386/zdravko/internal/models" -) - -func newHealthcheckHistory(db *gorm.DB, opts ...gen.DOOption) healthcheckHistory { - _healthcheckHistory := healthcheckHistory{} - - _healthcheckHistory.healthcheckHistoryDo.UseDB(db, opts...) - _healthcheckHistory.healthcheckHistoryDo.UseModel(&models.HealthcheckHistory{}) - - tableName := _healthcheckHistory.healthcheckHistoryDo.TableName() - _healthcheckHistory.ALL = field.NewAsterisk(tableName) - _healthcheckHistory.ID = field.NewUint(tableName, "id") - _healthcheckHistory.CreatedAt = field.NewTime(tableName, "created_at") - _healthcheckHistory.UpdatedAt = field.NewTime(tableName, "updated_at") - _healthcheckHistory.DeletedAt = field.NewField(tableName, "deleted_at") - _healthcheckHistory.Healthcheck = field.NewUint(tableName, "healthcheck") - _healthcheckHistory.Status = field.NewString(tableName, "status") - _healthcheckHistory.Note = field.NewString(tableName, "note") - - _healthcheckHistory.fillFieldMap() - - return _healthcheckHistory -} - -type healthcheckHistory struct { - healthcheckHistoryDo healthcheckHistoryDo - - ALL field.Asterisk - ID field.Uint - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Healthcheck field.Uint - Status field.String - Note field.String - - fieldMap map[string]field.Expr -} - -func (h healthcheckHistory) Table(newTableName string) *healthcheckHistory { - h.healthcheckHistoryDo.UseTable(newTableName) - return h.updateTableName(newTableName) -} - -func (h healthcheckHistory) As(alias string) *healthcheckHistory { - h.healthcheckHistoryDo.DO = *(h.healthcheckHistoryDo.As(alias).(*gen.DO)) - return h.updateTableName(alias) -} - -func (h *healthcheckHistory) updateTableName(table string) *healthcheckHistory { - h.ALL = field.NewAsterisk(table) - h.ID = field.NewUint(table, "id") - h.CreatedAt = field.NewTime(table, "created_at") - h.UpdatedAt = field.NewTime(table, "updated_at") - h.DeletedAt = field.NewField(table, "deleted_at") - h.Healthcheck = field.NewUint(table, "healthcheck") - h.Status = field.NewString(table, "status") - h.Note = field.NewString(table, "note") - - h.fillFieldMap() - - return h -} - -func (h *healthcheckHistory) WithContext(ctx context.Context) IHealthcheckHistoryDo { - return h.healthcheckHistoryDo.WithContext(ctx) -} - -func (h healthcheckHistory) TableName() string { return h.healthcheckHistoryDo.TableName() } - -func (h healthcheckHistory) Alias() string { return h.healthcheckHistoryDo.Alias() } - -func (h healthcheckHistory) Columns(cols ...field.Expr) gen.Columns { - return h.healthcheckHistoryDo.Columns(cols...) -} - -func (h *healthcheckHistory) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := h.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (h *healthcheckHistory) fillFieldMap() { - h.fieldMap = make(map[string]field.Expr, 7) - h.fieldMap["id"] = h.ID - h.fieldMap["created_at"] = h.CreatedAt - h.fieldMap["updated_at"] = h.UpdatedAt - h.fieldMap["deleted_at"] = h.DeletedAt - h.fieldMap["healthcheck"] = h.Healthcheck - h.fieldMap["status"] = h.Status - h.fieldMap["note"] = h.Note -} - -func (h healthcheckHistory) clone(db *gorm.DB) healthcheckHistory { - h.healthcheckHistoryDo.ReplaceConnPool(db.Statement.ConnPool) - return h -} - -func (h healthcheckHistory) replaceDB(db *gorm.DB) healthcheckHistory { - h.healthcheckHistoryDo.ReplaceDB(db) - return h -} - -type healthcheckHistoryDo struct{ gen.DO } - -type IHealthcheckHistoryDo interface { - gen.SubQuery - Debug() IHealthcheckHistoryDo - WithContext(ctx context.Context) IHealthcheckHistoryDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() IHealthcheckHistoryDo - WriteDB() IHealthcheckHistoryDo - As(alias string) gen.Dao - Session(config *gorm.Session) IHealthcheckHistoryDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) IHealthcheckHistoryDo - Not(conds ...gen.Condition) IHealthcheckHistoryDo - Or(conds ...gen.Condition) IHealthcheckHistoryDo - Select(conds ...field.Expr) IHealthcheckHistoryDo - Where(conds ...gen.Condition) IHealthcheckHistoryDo - Order(conds ...field.Expr) IHealthcheckHistoryDo - Distinct(cols ...field.Expr) IHealthcheckHistoryDo - Omit(cols ...field.Expr) IHealthcheckHistoryDo - Join(table schema.Tabler, on ...field.Expr) IHealthcheckHistoryDo - LeftJoin(table schema.Tabler, on ...field.Expr) IHealthcheckHistoryDo - RightJoin(table schema.Tabler, on ...field.Expr) IHealthcheckHistoryDo - Group(cols ...field.Expr) IHealthcheckHistoryDo - Having(conds ...gen.Condition) IHealthcheckHistoryDo - Limit(limit int) IHealthcheckHistoryDo - Offset(offset int) IHealthcheckHistoryDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) IHealthcheckHistoryDo - Unscoped() IHealthcheckHistoryDo - Create(values ...*models.HealthcheckHistory) error - CreateInBatches(values []*models.HealthcheckHistory, batchSize int) error - Save(values ...*models.HealthcheckHistory) error - First() (*models.HealthcheckHistory, error) - Take() (*models.HealthcheckHistory, error) - Last() (*models.HealthcheckHistory, error) - Find() ([]*models.HealthcheckHistory, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.HealthcheckHistory, err error) - FindInBatches(result *[]*models.HealthcheckHistory, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.HealthcheckHistory) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) IHealthcheckHistoryDo - Assign(attrs ...field.AssignExpr) IHealthcheckHistoryDo - Joins(fields ...field.RelationField) IHealthcheckHistoryDo - Preload(fields ...field.RelationField) IHealthcheckHistoryDo - FirstOrInit() (*models.HealthcheckHistory, error) - FirstOrCreate() (*models.HealthcheckHistory, error) - FindByPage(offset int, limit int) (result []*models.HealthcheckHistory, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) IHealthcheckHistoryDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (h healthcheckHistoryDo) Debug() IHealthcheckHistoryDo { - return h.withDO(h.DO.Debug()) -} - -func (h healthcheckHistoryDo) WithContext(ctx context.Context) IHealthcheckHistoryDo { - return h.withDO(h.DO.WithContext(ctx)) -} - -func (h healthcheckHistoryDo) ReadDB() IHealthcheckHistoryDo { - return h.Clauses(dbresolver.Read) -} - -func (h healthcheckHistoryDo) WriteDB() IHealthcheckHistoryDo { - return h.Clauses(dbresolver.Write) -} - -func (h healthcheckHistoryDo) Session(config *gorm.Session) IHealthcheckHistoryDo { - return h.withDO(h.DO.Session(config)) -} - -func (h healthcheckHistoryDo) Clauses(conds ...clause.Expression) IHealthcheckHistoryDo { - return h.withDO(h.DO.Clauses(conds...)) -} - -func (h healthcheckHistoryDo) Returning(value interface{}, columns ...string) IHealthcheckHistoryDo { - return h.withDO(h.DO.Returning(value, columns...)) -} - -func (h healthcheckHistoryDo) Not(conds ...gen.Condition) IHealthcheckHistoryDo { - return h.withDO(h.DO.Not(conds...)) -} - -func (h healthcheckHistoryDo) Or(conds ...gen.Condition) IHealthcheckHistoryDo { - return h.withDO(h.DO.Or(conds...)) -} - -func (h healthcheckHistoryDo) Select(conds ...field.Expr) IHealthcheckHistoryDo { - return h.withDO(h.DO.Select(conds...)) -} - -func (h healthcheckHistoryDo) Where(conds ...gen.Condition) IHealthcheckHistoryDo { - return h.withDO(h.DO.Where(conds...)) -} - -func (h healthcheckHistoryDo) Order(conds ...field.Expr) IHealthcheckHistoryDo { - return h.withDO(h.DO.Order(conds...)) -} - -func (h healthcheckHistoryDo) Distinct(cols ...field.Expr) IHealthcheckHistoryDo { - return h.withDO(h.DO.Distinct(cols...)) -} - -func (h healthcheckHistoryDo) Omit(cols ...field.Expr) IHealthcheckHistoryDo { - return h.withDO(h.DO.Omit(cols...)) -} - -func (h healthcheckHistoryDo) Join(table schema.Tabler, on ...field.Expr) IHealthcheckHistoryDo { - return h.withDO(h.DO.Join(table, on...)) -} - -func (h healthcheckHistoryDo) LeftJoin(table schema.Tabler, on ...field.Expr) IHealthcheckHistoryDo { - return h.withDO(h.DO.LeftJoin(table, on...)) -} - -func (h healthcheckHistoryDo) RightJoin(table schema.Tabler, on ...field.Expr) IHealthcheckHistoryDo { - return h.withDO(h.DO.RightJoin(table, on...)) -} - -func (h healthcheckHistoryDo) Group(cols ...field.Expr) IHealthcheckHistoryDo { - return h.withDO(h.DO.Group(cols...)) -} - -func (h healthcheckHistoryDo) Having(conds ...gen.Condition) IHealthcheckHistoryDo { - return h.withDO(h.DO.Having(conds...)) -} - -func (h healthcheckHistoryDo) Limit(limit int) IHealthcheckHistoryDo { - return h.withDO(h.DO.Limit(limit)) -} - -func (h healthcheckHistoryDo) Offset(offset int) IHealthcheckHistoryDo { - return h.withDO(h.DO.Offset(offset)) -} - -func (h healthcheckHistoryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IHealthcheckHistoryDo { - return h.withDO(h.DO.Scopes(funcs...)) -} - -func (h healthcheckHistoryDo) Unscoped() IHealthcheckHistoryDo { - return h.withDO(h.DO.Unscoped()) -} - -func (h healthcheckHistoryDo) Create(values ...*models.HealthcheckHistory) error { - if len(values) == 0 { - return nil - } - return h.DO.Create(values) -} - -func (h healthcheckHistoryDo) CreateInBatches(values []*models.HealthcheckHistory, batchSize int) error { - return h.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (h healthcheckHistoryDo) Save(values ...*models.HealthcheckHistory) error { - if len(values) == 0 { - return nil - } - return h.DO.Save(values) -} - -func (h healthcheckHistoryDo) First() (*models.HealthcheckHistory, error) { - if result, err := h.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.HealthcheckHistory), nil - } -} - -func (h healthcheckHistoryDo) Take() (*models.HealthcheckHistory, error) { - if result, err := h.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.HealthcheckHistory), nil - } -} - -func (h healthcheckHistoryDo) Last() (*models.HealthcheckHistory, error) { - if result, err := h.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.HealthcheckHistory), nil - } -} - -func (h healthcheckHistoryDo) Find() ([]*models.HealthcheckHistory, error) { - result, err := h.DO.Find() - return result.([]*models.HealthcheckHistory), err -} - -func (h healthcheckHistoryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.HealthcheckHistory, err error) { - buf := make([]*models.HealthcheckHistory, 0, batchSize) - err = h.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (h healthcheckHistoryDo) FindInBatches(result *[]*models.HealthcheckHistory, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return h.DO.FindInBatches(result, batchSize, fc) -} - -func (h healthcheckHistoryDo) Attrs(attrs ...field.AssignExpr) IHealthcheckHistoryDo { - return h.withDO(h.DO.Attrs(attrs...)) -} - -func (h healthcheckHistoryDo) Assign(attrs ...field.AssignExpr) IHealthcheckHistoryDo { - return h.withDO(h.DO.Assign(attrs...)) -} - -func (h healthcheckHistoryDo) Joins(fields ...field.RelationField) IHealthcheckHistoryDo { - for _, _f := range fields { - h = *h.withDO(h.DO.Joins(_f)) - } - return &h -} - -func (h healthcheckHistoryDo) Preload(fields ...field.RelationField) IHealthcheckHistoryDo { - for _, _f := range fields { - h = *h.withDO(h.DO.Preload(_f)) - } - return &h -} - -func (h healthcheckHistoryDo) FirstOrInit() (*models.HealthcheckHistory, error) { - if result, err := h.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.HealthcheckHistory), nil - } -} - -func (h healthcheckHistoryDo) FirstOrCreate() (*models.HealthcheckHistory, error) { - if result, err := h.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.HealthcheckHistory), nil - } -} - -func (h healthcheckHistoryDo) FindByPage(offset int, limit int) (result []*models.HealthcheckHistory, count int64, err error) { - result, err = h.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = h.Offset(-1).Limit(-1).Count() - return -} - -func (h healthcheckHistoryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = h.Count() - if err != nil { - return - } - - err = h.Offset(offset).Limit(limit).Scan(result) - return -} - -func (h healthcheckHistoryDo) Scan(result interface{}) (err error) { - return h.DO.Scan(result) -} - -func (h healthcheckHistoryDo) Delete(models ...*models.HealthcheckHistory) (result gen.ResultInfo, err error) { - return h.DO.Delete(models) -} - -func (h *healthcheckHistoryDo) withDO(do gen.Dao) *healthcheckHistoryDo { - h.DO = *do.(*gen.DO) - return h -} diff --git a/internal/models/query/healthchecks.gen.go b/internal/models/query/healthchecks.gen.go deleted file mode 100644 index 878978f..0000000 --- a/internal/models/query/healthchecks.gen.go +++ /dev/null @@ -1,500 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "code.tjo.space/mentos1386/zdravko/internal/models" -) - -func newHealthcheck(db *gorm.DB, opts ...gen.DOOption) healthcheck { - _healthcheck := healthcheck{} - - _healthcheck.healthcheckDo.UseDB(db, opts...) - _healthcheck.healthcheckDo.UseModel(&models.Healthcheck{}) - - tableName := _healthcheck.healthcheckDo.TableName() - _healthcheck.ALL = field.NewAsterisk(tableName) - _healthcheck.ID = field.NewUint(tableName, "id") - _healthcheck.CreatedAt = field.NewTime(tableName, "created_at") - _healthcheck.UpdatedAt = field.NewTime(tableName, "updated_at") - _healthcheck.DeletedAt = field.NewField(tableName, "deleted_at") - _healthcheck.Slug = field.NewString(tableName, "slug") - _healthcheck.Name = field.NewString(tableName, "name") - _healthcheck.Schedule = field.NewString(tableName, "schedule") - _healthcheck.WorkerGroups = field.NewField(tableName, "worker_groups") - _healthcheck.Script = field.NewString(tableName, "script") - _healthcheck.History = healthcheckHasManyHistory{ - db: db.Session(&gorm.Session{}), - - RelationField: field.NewRelation("History", "models.HealthcheckHistory"), - } - - _healthcheck.fillFieldMap() - - return _healthcheck -} - -type healthcheck struct { - healthcheckDo healthcheckDo - - ALL field.Asterisk - ID field.Uint - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Slug field.String - Name field.String - Schedule field.String - WorkerGroups field.Field - Script field.String - History healthcheckHasManyHistory - - fieldMap map[string]field.Expr -} - -func (h healthcheck) Table(newTableName string) *healthcheck { - h.healthcheckDo.UseTable(newTableName) - return h.updateTableName(newTableName) -} - -func (h healthcheck) As(alias string) *healthcheck { - h.healthcheckDo.DO = *(h.healthcheckDo.As(alias).(*gen.DO)) - return h.updateTableName(alias) -} - -func (h *healthcheck) updateTableName(table string) *healthcheck { - h.ALL = field.NewAsterisk(table) - h.ID = field.NewUint(table, "id") - h.CreatedAt = field.NewTime(table, "created_at") - h.UpdatedAt = field.NewTime(table, "updated_at") - h.DeletedAt = field.NewField(table, "deleted_at") - h.Slug = field.NewString(table, "slug") - h.Name = field.NewString(table, "name") - h.Schedule = field.NewString(table, "schedule") - h.WorkerGroups = field.NewField(table, "worker_groups") - h.Script = field.NewString(table, "script") - - h.fillFieldMap() - - return h -} - -func (h *healthcheck) WithContext(ctx context.Context) IHealthcheckDo { - return h.healthcheckDo.WithContext(ctx) -} - -func (h healthcheck) TableName() string { return h.healthcheckDo.TableName() } - -func (h healthcheck) Alias() string { return h.healthcheckDo.Alias() } - -func (h healthcheck) Columns(cols ...field.Expr) gen.Columns { return h.healthcheckDo.Columns(cols...) } - -func (h *healthcheck) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := h.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (h *healthcheck) fillFieldMap() { - h.fieldMap = make(map[string]field.Expr, 10) - h.fieldMap["id"] = h.ID - h.fieldMap["created_at"] = h.CreatedAt - h.fieldMap["updated_at"] = h.UpdatedAt - h.fieldMap["deleted_at"] = h.DeletedAt - h.fieldMap["slug"] = h.Slug - h.fieldMap["name"] = h.Name - h.fieldMap["schedule"] = h.Schedule - h.fieldMap["worker_groups"] = h.WorkerGroups - h.fieldMap["script"] = h.Script - -} - -func (h healthcheck) clone(db *gorm.DB) healthcheck { - h.healthcheckDo.ReplaceConnPool(db.Statement.ConnPool) - return h -} - -func (h healthcheck) replaceDB(db *gorm.DB) healthcheck { - h.healthcheckDo.ReplaceDB(db) - return h -} - -type healthcheckHasManyHistory struct { - db *gorm.DB - - field.RelationField -} - -func (a healthcheckHasManyHistory) Where(conds ...field.Expr) *healthcheckHasManyHistory { - if len(conds) == 0 { - return &a - } - - exprs := make([]clause.Expression, 0, len(conds)) - for _, cond := range conds { - exprs = append(exprs, cond.BeCond().(clause.Expression)) - } - a.db = a.db.Clauses(clause.Where{Exprs: exprs}) - return &a -} - -func (a healthcheckHasManyHistory) WithContext(ctx context.Context) *healthcheckHasManyHistory { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a healthcheckHasManyHistory) Session(session *gorm.Session) *healthcheckHasManyHistory { - a.db = a.db.Session(session) - return &a -} - -func (a healthcheckHasManyHistory) Model(m *models.Healthcheck) *healthcheckHasManyHistoryTx { - return &healthcheckHasManyHistoryTx{a.db.Model(m).Association(a.Name())} -} - -type healthcheckHasManyHistoryTx struct{ tx *gorm.Association } - -func (a healthcheckHasManyHistoryTx) Find() (result []*models.HealthcheckHistory, err error) { - return result, a.tx.Find(&result) -} - -func (a healthcheckHasManyHistoryTx) Append(values ...*models.HealthcheckHistory) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a healthcheckHasManyHistoryTx) Replace(values ...*models.HealthcheckHistory) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a healthcheckHasManyHistoryTx) Delete(values ...*models.HealthcheckHistory) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a healthcheckHasManyHistoryTx) Clear() error { - return a.tx.Clear() -} - -func (a healthcheckHasManyHistoryTx) Count() int64 { - return a.tx.Count() -} - -type healthcheckDo struct{ gen.DO } - -type IHealthcheckDo interface { - gen.SubQuery - Debug() IHealthcheckDo - WithContext(ctx context.Context) IHealthcheckDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() IHealthcheckDo - WriteDB() IHealthcheckDo - As(alias string) gen.Dao - Session(config *gorm.Session) IHealthcheckDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) IHealthcheckDo - Not(conds ...gen.Condition) IHealthcheckDo - Or(conds ...gen.Condition) IHealthcheckDo - Select(conds ...field.Expr) IHealthcheckDo - Where(conds ...gen.Condition) IHealthcheckDo - Order(conds ...field.Expr) IHealthcheckDo - Distinct(cols ...field.Expr) IHealthcheckDo - Omit(cols ...field.Expr) IHealthcheckDo - Join(table schema.Tabler, on ...field.Expr) IHealthcheckDo - LeftJoin(table schema.Tabler, on ...field.Expr) IHealthcheckDo - RightJoin(table schema.Tabler, on ...field.Expr) IHealthcheckDo - Group(cols ...field.Expr) IHealthcheckDo - Having(conds ...gen.Condition) IHealthcheckDo - Limit(limit int) IHealthcheckDo - Offset(offset int) IHealthcheckDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) IHealthcheckDo - Unscoped() IHealthcheckDo - Create(values ...*models.Healthcheck) error - CreateInBatches(values []*models.Healthcheck, batchSize int) error - Save(values ...*models.Healthcheck) error - First() (*models.Healthcheck, error) - Take() (*models.Healthcheck, error) - Last() (*models.Healthcheck, error) - Find() ([]*models.Healthcheck, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Healthcheck, err error) - FindInBatches(result *[]*models.Healthcheck, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.Healthcheck) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) IHealthcheckDo - Assign(attrs ...field.AssignExpr) IHealthcheckDo - Joins(fields ...field.RelationField) IHealthcheckDo - Preload(fields ...field.RelationField) IHealthcheckDo - FirstOrInit() (*models.Healthcheck, error) - FirstOrCreate() (*models.Healthcheck, error) - FindByPage(offset int, limit int) (result []*models.Healthcheck, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) IHealthcheckDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (h healthcheckDo) Debug() IHealthcheckDo { - return h.withDO(h.DO.Debug()) -} - -func (h healthcheckDo) WithContext(ctx context.Context) IHealthcheckDo { - return h.withDO(h.DO.WithContext(ctx)) -} - -func (h healthcheckDo) ReadDB() IHealthcheckDo { - return h.Clauses(dbresolver.Read) -} - -func (h healthcheckDo) WriteDB() IHealthcheckDo { - return h.Clauses(dbresolver.Write) -} - -func (h healthcheckDo) Session(config *gorm.Session) IHealthcheckDo { - return h.withDO(h.DO.Session(config)) -} - -func (h healthcheckDo) Clauses(conds ...clause.Expression) IHealthcheckDo { - return h.withDO(h.DO.Clauses(conds...)) -} - -func (h healthcheckDo) Returning(value interface{}, columns ...string) IHealthcheckDo { - return h.withDO(h.DO.Returning(value, columns...)) -} - -func (h healthcheckDo) Not(conds ...gen.Condition) IHealthcheckDo { - return h.withDO(h.DO.Not(conds...)) -} - -func (h healthcheckDo) Or(conds ...gen.Condition) IHealthcheckDo { - return h.withDO(h.DO.Or(conds...)) -} - -func (h healthcheckDo) Select(conds ...field.Expr) IHealthcheckDo { - return h.withDO(h.DO.Select(conds...)) -} - -func (h healthcheckDo) Where(conds ...gen.Condition) IHealthcheckDo { - return h.withDO(h.DO.Where(conds...)) -} - -func (h healthcheckDo) Order(conds ...field.Expr) IHealthcheckDo { - return h.withDO(h.DO.Order(conds...)) -} - -func (h healthcheckDo) Distinct(cols ...field.Expr) IHealthcheckDo { - return h.withDO(h.DO.Distinct(cols...)) -} - -func (h healthcheckDo) Omit(cols ...field.Expr) IHealthcheckDo { - return h.withDO(h.DO.Omit(cols...)) -} - -func (h healthcheckDo) Join(table schema.Tabler, on ...field.Expr) IHealthcheckDo { - return h.withDO(h.DO.Join(table, on...)) -} - -func (h healthcheckDo) LeftJoin(table schema.Tabler, on ...field.Expr) IHealthcheckDo { - return h.withDO(h.DO.LeftJoin(table, on...)) -} - -func (h healthcheckDo) RightJoin(table schema.Tabler, on ...field.Expr) IHealthcheckDo { - return h.withDO(h.DO.RightJoin(table, on...)) -} - -func (h healthcheckDo) Group(cols ...field.Expr) IHealthcheckDo { - return h.withDO(h.DO.Group(cols...)) -} - -func (h healthcheckDo) Having(conds ...gen.Condition) IHealthcheckDo { - return h.withDO(h.DO.Having(conds...)) -} - -func (h healthcheckDo) Limit(limit int) IHealthcheckDo { - return h.withDO(h.DO.Limit(limit)) -} - -func (h healthcheckDo) Offset(offset int) IHealthcheckDo { - return h.withDO(h.DO.Offset(offset)) -} - -func (h healthcheckDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IHealthcheckDo { - return h.withDO(h.DO.Scopes(funcs...)) -} - -func (h healthcheckDo) Unscoped() IHealthcheckDo { - return h.withDO(h.DO.Unscoped()) -} - -func (h healthcheckDo) Create(values ...*models.Healthcheck) error { - if len(values) == 0 { - return nil - } - return h.DO.Create(values) -} - -func (h healthcheckDo) CreateInBatches(values []*models.Healthcheck, batchSize int) error { - return h.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (h healthcheckDo) Save(values ...*models.Healthcheck) error { - if len(values) == 0 { - return nil - } - return h.DO.Save(values) -} - -func (h healthcheckDo) First() (*models.Healthcheck, error) { - if result, err := h.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.Healthcheck), nil - } -} - -func (h healthcheckDo) Take() (*models.Healthcheck, error) { - if result, err := h.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.Healthcheck), nil - } -} - -func (h healthcheckDo) Last() (*models.Healthcheck, error) { - if result, err := h.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.Healthcheck), nil - } -} - -func (h healthcheckDo) Find() ([]*models.Healthcheck, error) { - result, err := h.DO.Find() - return result.([]*models.Healthcheck), err -} - -func (h healthcheckDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Healthcheck, err error) { - buf := make([]*models.Healthcheck, 0, batchSize) - err = h.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (h healthcheckDo) FindInBatches(result *[]*models.Healthcheck, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return h.DO.FindInBatches(result, batchSize, fc) -} - -func (h healthcheckDo) Attrs(attrs ...field.AssignExpr) IHealthcheckDo { - return h.withDO(h.DO.Attrs(attrs...)) -} - -func (h healthcheckDo) Assign(attrs ...field.AssignExpr) IHealthcheckDo { - return h.withDO(h.DO.Assign(attrs...)) -} - -func (h healthcheckDo) Joins(fields ...field.RelationField) IHealthcheckDo { - for _, _f := range fields { - h = *h.withDO(h.DO.Joins(_f)) - } - return &h -} - -func (h healthcheckDo) Preload(fields ...field.RelationField) IHealthcheckDo { - for _, _f := range fields { - h = *h.withDO(h.DO.Preload(_f)) - } - return &h -} - -func (h healthcheckDo) FirstOrInit() (*models.Healthcheck, error) { - if result, err := h.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.Healthcheck), nil - } -} - -func (h healthcheckDo) FirstOrCreate() (*models.Healthcheck, error) { - if result, err := h.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.Healthcheck), nil - } -} - -func (h healthcheckDo) FindByPage(offset int, limit int) (result []*models.Healthcheck, count int64, err error) { - result, err = h.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = h.Offset(-1).Limit(-1).Count() - return -} - -func (h healthcheckDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = h.Count() - if err != nil { - return - } - - err = h.Offset(offset).Limit(limit).Scan(result) - return -} - -func (h healthcheckDo) Scan(result interface{}) (err error) { - return h.DO.Scan(result) -} - -func (h healthcheckDo) Delete(models ...*models.Healthcheck) (result gen.ResultInfo, err error) { - return h.DO.Delete(models) -} - -func (h *healthcheckDo) withDO(do gen.Dao) *healthcheckDo { - h.DO = *do.(*gen.DO) - return h -} diff --git a/internal/models/query/monitor_histories.gen.go b/internal/models/query/monitor_histories.gen.go new file mode 100644 index 0000000..c3f2b3e --- /dev/null +++ b/internal/models/query/monitor_histories.gen.go @@ -0,0 +1,416 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "gorm.io/gen" + "gorm.io/gen/field" + + "gorm.io/plugin/dbresolver" + + "code.tjo.space/mentos1386/zdravko/internal/models" +) + +func newMonitorHistory(db *gorm.DB, opts ...gen.DOOption) monitorHistory { + _monitorHistory := monitorHistory{} + + _monitorHistory.monitorHistoryDo.UseDB(db, opts...) + _monitorHistory.monitorHistoryDo.UseModel(&models.MonitorHistory{}) + + tableName := _monitorHistory.monitorHistoryDo.TableName() + _monitorHistory.ALL = field.NewAsterisk(tableName) + _monitorHistory.ID = field.NewUint(tableName, "id") + _monitorHistory.CreatedAt = field.NewTime(tableName, "created_at") + _monitorHistory.UpdatedAt = field.NewTime(tableName, "updated_at") + _monitorHistory.DeletedAt = field.NewField(tableName, "deleted_at") + _monitorHistory.Monitor = field.NewUint(tableName, "monitor") + _monitorHistory.Status = field.NewString(tableName, "status") + _monitorHistory.Note = field.NewString(tableName, "note") + + _monitorHistory.fillFieldMap() + + return _monitorHistory +} + +type monitorHistory struct { + monitorHistoryDo monitorHistoryDo + + ALL field.Asterisk + ID field.Uint + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + Monitor field.Uint + Status field.String + Note field.String + + fieldMap map[string]field.Expr +} + +func (m monitorHistory) Table(newTableName string) *monitorHistory { + m.monitorHistoryDo.UseTable(newTableName) + return m.updateTableName(newTableName) +} + +func (m monitorHistory) As(alias string) *monitorHistory { + m.monitorHistoryDo.DO = *(m.monitorHistoryDo.As(alias).(*gen.DO)) + return m.updateTableName(alias) +} + +func (m *monitorHistory) updateTableName(table string) *monitorHistory { + m.ALL = field.NewAsterisk(table) + m.ID = field.NewUint(table, "id") + m.CreatedAt = field.NewTime(table, "created_at") + m.UpdatedAt = field.NewTime(table, "updated_at") + m.DeletedAt = field.NewField(table, "deleted_at") + m.Monitor = field.NewUint(table, "monitor") + m.Status = field.NewString(table, "status") + m.Note = field.NewString(table, "note") + + m.fillFieldMap() + + return m +} + +func (m *monitorHistory) WithContext(ctx context.Context) IMonitorHistoryDo { + return m.monitorHistoryDo.WithContext(ctx) +} + +func (m monitorHistory) TableName() string { return m.monitorHistoryDo.TableName() } + +func (m monitorHistory) Alias() string { return m.monitorHistoryDo.Alias() } + +func (m monitorHistory) Columns(cols ...field.Expr) gen.Columns { + return m.monitorHistoryDo.Columns(cols...) +} + +func (m *monitorHistory) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := m.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (m *monitorHistory) fillFieldMap() { + m.fieldMap = make(map[string]field.Expr, 7) + m.fieldMap["id"] = m.ID + m.fieldMap["created_at"] = m.CreatedAt + m.fieldMap["updated_at"] = m.UpdatedAt + m.fieldMap["deleted_at"] = m.DeletedAt + m.fieldMap["monitor"] = m.Monitor + m.fieldMap["status"] = m.Status + m.fieldMap["note"] = m.Note +} + +func (m monitorHistory) clone(db *gorm.DB) monitorHistory { + m.monitorHistoryDo.ReplaceConnPool(db.Statement.ConnPool) + return m +} + +func (m monitorHistory) replaceDB(db *gorm.DB) monitorHistory { + m.monitorHistoryDo.ReplaceDB(db) + return m +} + +type monitorHistoryDo struct{ gen.DO } + +type IMonitorHistoryDo interface { + gen.SubQuery + Debug() IMonitorHistoryDo + WithContext(ctx context.Context) IMonitorHistoryDo + WithResult(fc func(tx gen.Dao)) gen.ResultInfo + ReplaceDB(db *gorm.DB) + ReadDB() IMonitorHistoryDo + WriteDB() IMonitorHistoryDo + As(alias string) gen.Dao + Session(config *gorm.Session) IMonitorHistoryDo + Columns(cols ...field.Expr) gen.Columns + Clauses(conds ...clause.Expression) IMonitorHistoryDo + Not(conds ...gen.Condition) IMonitorHistoryDo + Or(conds ...gen.Condition) IMonitorHistoryDo + Select(conds ...field.Expr) IMonitorHistoryDo + Where(conds ...gen.Condition) IMonitorHistoryDo + Order(conds ...field.Expr) IMonitorHistoryDo + Distinct(cols ...field.Expr) IMonitorHistoryDo + Omit(cols ...field.Expr) IMonitorHistoryDo + Join(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo + LeftJoin(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo + RightJoin(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo + Group(cols ...field.Expr) IMonitorHistoryDo + Having(conds ...gen.Condition) IMonitorHistoryDo + Limit(limit int) IMonitorHistoryDo + Offset(offset int) IMonitorHistoryDo + Count() (count int64, err error) + Scopes(funcs ...func(gen.Dao) gen.Dao) IMonitorHistoryDo + Unscoped() IMonitorHistoryDo + Create(values ...*models.MonitorHistory) error + CreateInBatches(values []*models.MonitorHistory, batchSize int) error + Save(values ...*models.MonitorHistory) error + First() (*models.MonitorHistory, error) + Take() (*models.MonitorHistory, error) + Last() (*models.MonitorHistory, error) + Find() ([]*models.MonitorHistory, error) + FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.MonitorHistory, err error) + FindInBatches(result *[]*models.MonitorHistory, batchSize int, fc func(tx gen.Dao, batch int) error) error + Pluck(column field.Expr, dest interface{}) error + Delete(...*models.MonitorHistory) (info gen.ResultInfo, err error) + Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + Updates(value interface{}) (info gen.ResultInfo, err error) + UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + UpdateColumns(value interface{}) (info gen.ResultInfo, err error) + UpdateFrom(q gen.SubQuery) gen.Dao + Attrs(attrs ...field.AssignExpr) IMonitorHistoryDo + Assign(attrs ...field.AssignExpr) IMonitorHistoryDo + Joins(fields ...field.RelationField) IMonitorHistoryDo + Preload(fields ...field.RelationField) IMonitorHistoryDo + FirstOrInit() (*models.MonitorHistory, error) + FirstOrCreate() (*models.MonitorHistory, error) + FindByPage(offset int, limit int) (result []*models.MonitorHistory, count int64, err error) + ScanByPage(result interface{}, offset int, limit int) (count int64, err error) + Scan(result interface{}) (err error) + Returning(value interface{}, columns ...string) IMonitorHistoryDo + UnderlyingDB() *gorm.DB + schema.Tabler +} + +func (m monitorHistoryDo) Debug() IMonitorHistoryDo { + return m.withDO(m.DO.Debug()) +} + +func (m monitorHistoryDo) WithContext(ctx context.Context) IMonitorHistoryDo { + return m.withDO(m.DO.WithContext(ctx)) +} + +func (m monitorHistoryDo) ReadDB() IMonitorHistoryDo { + return m.Clauses(dbresolver.Read) +} + +func (m monitorHistoryDo) WriteDB() IMonitorHistoryDo { + return m.Clauses(dbresolver.Write) +} + +func (m monitorHistoryDo) Session(config *gorm.Session) IMonitorHistoryDo { + return m.withDO(m.DO.Session(config)) +} + +func (m monitorHistoryDo) Clauses(conds ...clause.Expression) IMonitorHistoryDo { + return m.withDO(m.DO.Clauses(conds...)) +} + +func (m monitorHistoryDo) Returning(value interface{}, columns ...string) IMonitorHistoryDo { + return m.withDO(m.DO.Returning(value, columns...)) +} + +func (m monitorHistoryDo) Not(conds ...gen.Condition) IMonitorHistoryDo { + return m.withDO(m.DO.Not(conds...)) +} + +func (m monitorHistoryDo) Or(conds ...gen.Condition) IMonitorHistoryDo { + return m.withDO(m.DO.Or(conds...)) +} + +func (m monitorHistoryDo) Select(conds ...field.Expr) IMonitorHistoryDo { + return m.withDO(m.DO.Select(conds...)) +} + +func (m monitorHistoryDo) Where(conds ...gen.Condition) IMonitorHistoryDo { + return m.withDO(m.DO.Where(conds...)) +} + +func (m monitorHistoryDo) Order(conds ...field.Expr) IMonitorHistoryDo { + return m.withDO(m.DO.Order(conds...)) +} + +func (m monitorHistoryDo) Distinct(cols ...field.Expr) IMonitorHistoryDo { + return m.withDO(m.DO.Distinct(cols...)) +} + +func (m monitorHistoryDo) Omit(cols ...field.Expr) IMonitorHistoryDo { + return m.withDO(m.DO.Omit(cols...)) +} + +func (m monitorHistoryDo) Join(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo { + return m.withDO(m.DO.Join(table, on...)) +} + +func (m monitorHistoryDo) LeftJoin(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo { + return m.withDO(m.DO.LeftJoin(table, on...)) +} + +func (m monitorHistoryDo) RightJoin(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo { + return m.withDO(m.DO.RightJoin(table, on...)) +} + +func (m monitorHistoryDo) Group(cols ...field.Expr) IMonitorHistoryDo { + return m.withDO(m.DO.Group(cols...)) +} + +func (m monitorHistoryDo) Having(conds ...gen.Condition) IMonitorHistoryDo { + return m.withDO(m.DO.Having(conds...)) +} + +func (m monitorHistoryDo) Limit(limit int) IMonitorHistoryDo { + return m.withDO(m.DO.Limit(limit)) +} + +func (m monitorHistoryDo) Offset(offset int) IMonitorHistoryDo { + return m.withDO(m.DO.Offset(offset)) +} + +func (m monitorHistoryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IMonitorHistoryDo { + return m.withDO(m.DO.Scopes(funcs...)) +} + +func (m monitorHistoryDo) Unscoped() IMonitorHistoryDo { + return m.withDO(m.DO.Unscoped()) +} + +func (m monitorHistoryDo) Create(values ...*models.MonitorHistory) error { + if len(values) == 0 { + return nil + } + return m.DO.Create(values) +} + +func (m monitorHistoryDo) CreateInBatches(values []*models.MonitorHistory, batchSize int) error { + return m.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (m monitorHistoryDo) Save(values ...*models.MonitorHistory) error { + if len(values) == 0 { + return nil + } + return m.DO.Save(values) +} + +func (m monitorHistoryDo) First() (*models.MonitorHistory, error) { + if result, err := m.DO.First(); err != nil { + return nil, err + } else { + return result.(*models.MonitorHistory), nil + } +} + +func (m monitorHistoryDo) Take() (*models.MonitorHistory, error) { + if result, err := m.DO.Take(); err != nil { + return nil, err + } else { + return result.(*models.MonitorHistory), nil + } +} + +func (m monitorHistoryDo) Last() (*models.MonitorHistory, error) { + if result, err := m.DO.Last(); err != nil { + return nil, err + } else { + return result.(*models.MonitorHistory), nil + } +} + +func (m monitorHistoryDo) Find() ([]*models.MonitorHistory, error) { + result, err := m.DO.Find() + return result.([]*models.MonitorHistory), err +} + +func (m monitorHistoryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.MonitorHistory, err error) { + buf := make([]*models.MonitorHistory, 0, batchSize) + err = m.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (m monitorHistoryDo) FindInBatches(result *[]*models.MonitorHistory, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return m.DO.FindInBatches(result, batchSize, fc) +} + +func (m monitorHistoryDo) Attrs(attrs ...field.AssignExpr) IMonitorHistoryDo { + return m.withDO(m.DO.Attrs(attrs...)) +} + +func (m monitorHistoryDo) Assign(attrs ...field.AssignExpr) IMonitorHistoryDo { + return m.withDO(m.DO.Assign(attrs...)) +} + +func (m monitorHistoryDo) Joins(fields ...field.RelationField) IMonitorHistoryDo { + for _, _f := range fields { + m = *m.withDO(m.DO.Joins(_f)) + } + return &m +} + +func (m monitorHistoryDo) Preload(fields ...field.RelationField) IMonitorHistoryDo { + for _, _f := range fields { + m = *m.withDO(m.DO.Preload(_f)) + } + return &m +} + +func (m monitorHistoryDo) FirstOrInit() (*models.MonitorHistory, error) { + if result, err := m.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*models.MonitorHistory), nil + } +} + +func (m monitorHistoryDo) FirstOrCreate() (*models.MonitorHistory, error) { + if result, err := m.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*models.MonitorHistory), nil + } +} + +func (m monitorHistoryDo) FindByPage(offset int, limit int) (result []*models.MonitorHistory, count int64, err error) { + result, err = m.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = m.Offset(-1).Limit(-1).Count() + return +} + +func (m monitorHistoryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = m.Count() + if err != nil { + return + } + + err = m.Offset(offset).Limit(limit).Scan(result) + return +} + +func (m monitorHistoryDo) Scan(result interface{}) (err error) { + return m.DO.Scan(result) +} + +func (m monitorHistoryDo) Delete(models ...*models.MonitorHistory) (result gen.ResultInfo, err error) { + return m.DO.Delete(models) +} + +func (m *monitorHistoryDo) withDO(do gen.Dao) *monitorHistoryDo { + m.DO = *do.(*gen.DO) + return m +} diff --git a/internal/models/query/monitors.gen.go b/internal/models/query/monitors.gen.go new file mode 100644 index 0000000..75729b2 --- /dev/null +++ b/internal/models/query/monitors.gen.go @@ -0,0 +1,498 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "gorm.io/gen" + "gorm.io/gen/field" + + "gorm.io/plugin/dbresolver" + + "code.tjo.space/mentos1386/zdravko/internal/models" +) + +func newMonitor(db *gorm.DB, opts ...gen.DOOption) monitor { + _monitor := monitor{} + + _monitor.monitorDo.UseDB(db, opts...) + _monitor.monitorDo.UseModel(&models.Monitor{}) + + tableName := _monitor.monitorDo.TableName() + _monitor.ALL = field.NewAsterisk(tableName) + _monitor.ID = field.NewUint(tableName, "id") + _monitor.CreatedAt = field.NewTime(tableName, "created_at") + _monitor.UpdatedAt = field.NewTime(tableName, "updated_at") + _monitor.DeletedAt = field.NewField(tableName, "deleted_at") + _monitor.Slug = field.NewString(tableName, "slug") + _monitor.Name = field.NewString(tableName, "name") + _monitor.Schedule = field.NewString(tableName, "schedule") + _monitor.WorkerGroups = field.NewField(tableName, "worker_groups") + _monitor.Script = field.NewString(tableName, "script") + _monitor.History = monitorHasManyHistory{ + db: db.Session(&gorm.Session{}), + + RelationField: field.NewRelation("History", "models.MonitorHistory"), + } + + _monitor.fillFieldMap() + + return _monitor +} + +type monitor struct { + monitorDo monitorDo + + ALL field.Asterisk + ID field.Uint + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + Slug field.String + Name field.String + Schedule field.String + WorkerGroups field.Field + Script field.String + History monitorHasManyHistory + + fieldMap map[string]field.Expr +} + +func (m monitor) Table(newTableName string) *monitor { + m.monitorDo.UseTable(newTableName) + return m.updateTableName(newTableName) +} + +func (m monitor) As(alias string) *monitor { + m.monitorDo.DO = *(m.monitorDo.As(alias).(*gen.DO)) + return m.updateTableName(alias) +} + +func (m *monitor) updateTableName(table string) *monitor { + m.ALL = field.NewAsterisk(table) + m.ID = field.NewUint(table, "id") + m.CreatedAt = field.NewTime(table, "created_at") + m.UpdatedAt = field.NewTime(table, "updated_at") + m.DeletedAt = field.NewField(table, "deleted_at") + m.Slug = field.NewString(table, "slug") + m.Name = field.NewString(table, "name") + m.Schedule = field.NewString(table, "schedule") + m.WorkerGroups = field.NewField(table, "worker_groups") + m.Script = field.NewString(table, "script") + + m.fillFieldMap() + + return m +} + +func (m *monitor) WithContext(ctx context.Context) IMonitorDo { return m.monitorDo.WithContext(ctx) } + +func (m monitor) TableName() string { return m.monitorDo.TableName() } + +func (m monitor) Alias() string { return m.monitorDo.Alias() } + +func (m monitor) Columns(cols ...field.Expr) gen.Columns { return m.monitorDo.Columns(cols...) } + +func (m *monitor) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := m.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (m *monitor) fillFieldMap() { + m.fieldMap = make(map[string]field.Expr, 10) + m.fieldMap["id"] = m.ID + m.fieldMap["created_at"] = m.CreatedAt + m.fieldMap["updated_at"] = m.UpdatedAt + m.fieldMap["deleted_at"] = m.DeletedAt + m.fieldMap["slug"] = m.Slug + m.fieldMap["name"] = m.Name + m.fieldMap["schedule"] = m.Schedule + m.fieldMap["worker_groups"] = m.WorkerGroups + m.fieldMap["script"] = m.Script + +} + +func (m monitor) clone(db *gorm.DB) monitor { + m.monitorDo.ReplaceConnPool(db.Statement.ConnPool) + return m +} + +func (m monitor) replaceDB(db *gorm.DB) monitor { + m.monitorDo.ReplaceDB(db) + return m +} + +type monitorHasManyHistory struct { + db *gorm.DB + + field.RelationField +} + +func (a monitorHasManyHistory) Where(conds ...field.Expr) *monitorHasManyHistory { + if len(conds) == 0 { + return &a + } + + exprs := make([]clause.Expression, 0, len(conds)) + for _, cond := range conds { + exprs = append(exprs, cond.BeCond().(clause.Expression)) + } + a.db = a.db.Clauses(clause.Where{Exprs: exprs}) + return &a +} + +func (a monitorHasManyHistory) WithContext(ctx context.Context) *monitorHasManyHistory { + a.db = a.db.WithContext(ctx) + return &a +} + +func (a monitorHasManyHistory) Session(session *gorm.Session) *monitorHasManyHistory { + a.db = a.db.Session(session) + return &a +} + +func (a monitorHasManyHistory) Model(m *models.Monitor) *monitorHasManyHistoryTx { + return &monitorHasManyHistoryTx{a.db.Model(m).Association(a.Name())} +} + +type monitorHasManyHistoryTx struct{ tx *gorm.Association } + +func (a monitorHasManyHistoryTx) Find() (result []*models.MonitorHistory, err error) { + return result, a.tx.Find(&result) +} + +func (a monitorHasManyHistoryTx) Append(values ...*models.MonitorHistory) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Append(targetValues...) +} + +func (a monitorHasManyHistoryTx) Replace(values ...*models.MonitorHistory) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Replace(targetValues...) +} + +func (a monitorHasManyHistoryTx) Delete(values ...*models.MonitorHistory) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Delete(targetValues...) +} + +func (a monitorHasManyHistoryTx) Clear() error { + return a.tx.Clear() +} + +func (a monitorHasManyHistoryTx) Count() int64 { + return a.tx.Count() +} + +type monitorDo struct{ gen.DO } + +type IMonitorDo interface { + gen.SubQuery + Debug() IMonitorDo + WithContext(ctx context.Context) IMonitorDo + WithResult(fc func(tx gen.Dao)) gen.ResultInfo + ReplaceDB(db *gorm.DB) + ReadDB() IMonitorDo + WriteDB() IMonitorDo + As(alias string) gen.Dao + Session(config *gorm.Session) IMonitorDo + Columns(cols ...field.Expr) gen.Columns + Clauses(conds ...clause.Expression) IMonitorDo + Not(conds ...gen.Condition) IMonitorDo + Or(conds ...gen.Condition) IMonitorDo + Select(conds ...field.Expr) IMonitorDo + Where(conds ...gen.Condition) IMonitorDo + Order(conds ...field.Expr) IMonitorDo + Distinct(cols ...field.Expr) IMonitorDo + Omit(cols ...field.Expr) IMonitorDo + Join(table schema.Tabler, on ...field.Expr) IMonitorDo + LeftJoin(table schema.Tabler, on ...field.Expr) IMonitorDo + RightJoin(table schema.Tabler, on ...field.Expr) IMonitorDo + Group(cols ...field.Expr) IMonitorDo + Having(conds ...gen.Condition) IMonitorDo + Limit(limit int) IMonitorDo + Offset(offset int) IMonitorDo + Count() (count int64, err error) + Scopes(funcs ...func(gen.Dao) gen.Dao) IMonitorDo + Unscoped() IMonitorDo + Create(values ...*models.Monitor) error + CreateInBatches(values []*models.Monitor, batchSize int) error + Save(values ...*models.Monitor) error + First() (*models.Monitor, error) + Take() (*models.Monitor, error) + Last() (*models.Monitor, error) + Find() ([]*models.Monitor, error) + FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Monitor, err error) + FindInBatches(result *[]*models.Monitor, batchSize int, fc func(tx gen.Dao, batch int) error) error + Pluck(column field.Expr, dest interface{}) error + Delete(...*models.Monitor) (info gen.ResultInfo, err error) + Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + Updates(value interface{}) (info gen.ResultInfo, err error) + UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + UpdateColumns(value interface{}) (info gen.ResultInfo, err error) + UpdateFrom(q gen.SubQuery) gen.Dao + Attrs(attrs ...field.AssignExpr) IMonitorDo + Assign(attrs ...field.AssignExpr) IMonitorDo + Joins(fields ...field.RelationField) IMonitorDo + Preload(fields ...field.RelationField) IMonitorDo + FirstOrInit() (*models.Monitor, error) + FirstOrCreate() (*models.Monitor, error) + FindByPage(offset int, limit int) (result []*models.Monitor, count int64, err error) + ScanByPage(result interface{}, offset int, limit int) (count int64, err error) + Scan(result interface{}) (err error) + Returning(value interface{}, columns ...string) IMonitorDo + UnderlyingDB() *gorm.DB + schema.Tabler +} + +func (m monitorDo) Debug() IMonitorDo { + return m.withDO(m.DO.Debug()) +} + +func (m monitorDo) WithContext(ctx context.Context) IMonitorDo { + return m.withDO(m.DO.WithContext(ctx)) +} + +func (m monitorDo) ReadDB() IMonitorDo { + return m.Clauses(dbresolver.Read) +} + +func (m monitorDo) WriteDB() IMonitorDo { + return m.Clauses(dbresolver.Write) +} + +func (m monitorDo) Session(config *gorm.Session) IMonitorDo { + return m.withDO(m.DO.Session(config)) +} + +func (m monitorDo) Clauses(conds ...clause.Expression) IMonitorDo { + return m.withDO(m.DO.Clauses(conds...)) +} + +func (m monitorDo) Returning(value interface{}, columns ...string) IMonitorDo { + return m.withDO(m.DO.Returning(value, columns...)) +} + +func (m monitorDo) Not(conds ...gen.Condition) IMonitorDo { + return m.withDO(m.DO.Not(conds...)) +} + +func (m monitorDo) Or(conds ...gen.Condition) IMonitorDo { + return m.withDO(m.DO.Or(conds...)) +} + +func (m monitorDo) Select(conds ...field.Expr) IMonitorDo { + return m.withDO(m.DO.Select(conds...)) +} + +func (m monitorDo) Where(conds ...gen.Condition) IMonitorDo { + return m.withDO(m.DO.Where(conds...)) +} + +func (m monitorDo) Order(conds ...field.Expr) IMonitorDo { + return m.withDO(m.DO.Order(conds...)) +} + +func (m monitorDo) Distinct(cols ...field.Expr) IMonitorDo { + return m.withDO(m.DO.Distinct(cols...)) +} + +func (m monitorDo) Omit(cols ...field.Expr) IMonitorDo { + return m.withDO(m.DO.Omit(cols...)) +} + +func (m monitorDo) Join(table schema.Tabler, on ...field.Expr) IMonitorDo { + return m.withDO(m.DO.Join(table, on...)) +} + +func (m monitorDo) LeftJoin(table schema.Tabler, on ...field.Expr) IMonitorDo { + return m.withDO(m.DO.LeftJoin(table, on...)) +} + +func (m monitorDo) RightJoin(table schema.Tabler, on ...field.Expr) IMonitorDo { + return m.withDO(m.DO.RightJoin(table, on...)) +} + +func (m monitorDo) Group(cols ...field.Expr) IMonitorDo { + return m.withDO(m.DO.Group(cols...)) +} + +func (m monitorDo) Having(conds ...gen.Condition) IMonitorDo { + return m.withDO(m.DO.Having(conds...)) +} + +func (m monitorDo) Limit(limit int) IMonitorDo { + return m.withDO(m.DO.Limit(limit)) +} + +func (m monitorDo) Offset(offset int) IMonitorDo { + return m.withDO(m.DO.Offset(offset)) +} + +func (m monitorDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IMonitorDo { + return m.withDO(m.DO.Scopes(funcs...)) +} + +func (m monitorDo) Unscoped() IMonitorDo { + return m.withDO(m.DO.Unscoped()) +} + +func (m monitorDo) Create(values ...*models.Monitor) error { + if len(values) == 0 { + return nil + } + return m.DO.Create(values) +} + +func (m monitorDo) CreateInBatches(values []*models.Monitor, batchSize int) error { + return m.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (m monitorDo) Save(values ...*models.Monitor) error { + if len(values) == 0 { + return nil + } + return m.DO.Save(values) +} + +func (m monitorDo) First() (*models.Monitor, error) { + if result, err := m.DO.First(); err != nil { + return nil, err + } else { + return result.(*models.Monitor), nil + } +} + +func (m monitorDo) Take() (*models.Monitor, error) { + if result, err := m.DO.Take(); err != nil { + return nil, err + } else { + return result.(*models.Monitor), nil + } +} + +func (m monitorDo) Last() (*models.Monitor, error) { + if result, err := m.DO.Last(); err != nil { + return nil, err + } else { + return result.(*models.Monitor), nil + } +} + +func (m monitorDo) Find() ([]*models.Monitor, error) { + result, err := m.DO.Find() + return result.([]*models.Monitor), err +} + +func (m monitorDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Monitor, err error) { + buf := make([]*models.Monitor, 0, batchSize) + err = m.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (m monitorDo) FindInBatches(result *[]*models.Monitor, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return m.DO.FindInBatches(result, batchSize, fc) +} + +func (m monitorDo) Attrs(attrs ...field.AssignExpr) IMonitorDo { + return m.withDO(m.DO.Attrs(attrs...)) +} + +func (m monitorDo) Assign(attrs ...field.AssignExpr) IMonitorDo { + return m.withDO(m.DO.Assign(attrs...)) +} + +func (m monitorDo) Joins(fields ...field.RelationField) IMonitorDo { + for _, _f := range fields { + m = *m.withDO(m.DO.Joins(_f)) + } + return &m +} + +func (m monitorDo) Preload(fields ...field.RelationField) IMonitorDo { + for _, _f := range fields { + m = *m.withDO(m.DO.Preload(_f)) + } + return &m +} + +func (m monitorDo) FirstOrInit() (*models.Monitor, error) { + if result, err := m.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*models.Monitor), nil + } +} + +func (m monitorDo) FirstOrCreate() (*models.Monitor, error) { + if result, err := m.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*models.Monitor), nil + } +} + +func (m monitorDo) FindByPage(offset int, limit int) (result []*models.Monitor, count int64, err error) { + result, err = m.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = m.Offset(-1).Limit(-1).Count() + return +} + +func (m monitorDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = m.Count() + if err != nil { + return + } + + err = m.Offset(offset).Limit(limit).Scan(result) + return +} + +func (m monitorDo) Scan(result interface{}) (err error) { + return m.DO.Scan(result) +} + +func (m monitorDo) Delete(models ...*models.Monitor) (result gen.ResultInfo, err error) { + return m.DO.Delete(models) +} + +func (m *monitorDo) withDO(do gen.Dao) *monitorDo { + m.DO = *do.(*gen.DO) + return m +} diff --git a/internal/services/healthcheck.go b/internal/services/healthcheck.go deleted file mode 100644 index 5d7eb33..0000000 --- a/internal/services/healthcheck.go +++ /dev/null @@ -1,114 +0,0 @@ -package services - -import ( - "context" - "log" - "time" - - "code.tjo.space/mentos1386/zdravko/internal/models" - "code.tjo.space/mentos1386/zdravko/internal/models/query" - "code.tjo.space/mentos1386/zdravko/internal/workflows" - "go.temporal.io/sdk/client" - "go.temporal.io/sdk/temporal" - "gorm.io/gorm" -) - -func getScheduleId(healthcheck *models.Healthcheck, group string) string { - return "healthcheck-" + healthcheck.Slug + "-" + group -} - -func CreateHealthcheck(ctx context.Context, query *query.Query, healthcheck *models.Healthcheck) error { - return query.Healthcheck.WithContext(ctx).Create(healthcheck) -} - -func UpdateHealthcheck(ctx context.Context, q *query.Query, healthcheck *models.Healthcheck) error { - _, err := q.Healthcheck.WithContext(ctx).Where( - q.Healthcheck.Slug.Eq(healthcheck.Slug), - ).Updates(healthcheck) - return err -} - -func GetHealthcheck(ctx context.Context, q *query.Query, slug string) (*models.Healthcheck, error) { - return q.Healthcheck.WithContext(ctx).Where( - q.Healthcheck.Slug.Eq(slug), - q.Healthcheck.DeletedAt.IsNull(), - ).Preload( - q.Healthcheck.History, - ).First() -} - -func GetHealthchecks(ctx context.Context, q *query.Query) ([]*models.Healthcheck, error) { - return q.Healthcheck.WithContext(ctx).Preload( - q.Healthcheck.History, - ).Where( - q.Healthcheck.DeletedAt.IsNull(), - ).Find() -} - -func CreateOrUpdateHealthcheckSchedule(ctx context.Context, t client.Client, healthcheck *models.Healthcheck) error { - log.Println("Creating or Updating Healthcheck Schedule") - - args := make([]interface{}, 0) - args = append(args, workflows.HealthcheckWorkflowParam{Script: healthcheck.Script, Slug: healthcheck.Slug}) - - for _, group := range healthcheck.WorkerGroups { - options := client.ScheduleOptions{ - ID: getScheduleId(healthcheck, group), - //SearchAttributes: map[string]interface{}{ - // "worker-group": group, - // "healthcheck-slug": healthcheck.Slug, - //}, - Spec: client.ScheduleSpec{ - CronExpressions: []string{healthcheck.Schedule}, - Jitter: time.Second * 10, - }, - Action: &client.ScheduleWorkflowAction{ - ID: getScheduleId(healthcheck, group), - Workflow: workflows.NewWorkflows(nil).HealthcheckWorkflowDefinition, - Args: args, - TaskQueue: group, - RetryPolicy: &temporal.RetryPolicy{ - MaximumAttempts: 3, - }, - }, - } - - schedule := t.ScheduleClient().GetHandle(ctx, getScheduleId(healthcheck, group)) - - // If exists, we update - _, err := schedule.Describe(ctx) - if err == nil { - err = schedule.Update(ctx, client.ScheduleUpdateOptions{ - DoUpdate: func(input client.ScheduleUpdateInput) (*client.ScheduleUpdate, error) { - return &client.ScheduleUpdate{ - Schedule: &client.Schedule{ - Spec: &options.Spec, - Action: options.Action, - Policy: input.Description.Schedule.Policy, - State: input.Description.Schedule.State, - }, - }, nil - }, - }) - if err != nil { - return err - } - } else { - schedule, err = t.ScheduleClient().Create(ctx, options) - if err != nil { - return err - } - } - - err = schedule.Trigger(ctx, client.ScheduleTriggerOptions{}) - if err != nil { - return err - } - } - - return nil -} - -func CreateHealthcheckHistory(ctx context.Context, db *gorm.DB, healthcheckHistory *models.HealthcheckHistory) error { - return db.WithContext(ctx).Create(healthcheckHistory).Error -} diff --git a/internal/services/monitor.go b/internal/services/monitor.go new file mode 100644 index 0000000..b6607b2 --- /dev/null +++ b/internal/services/monitor.go @@ -0,0 +1,114 @@ +package services + +import ( + "context" + "log" + "time" + + "code.tjo.space/mentos1386/zdravko/internal/models" + "code.tjo.space/mentos1386/zdravko/internal/models/query" + "code.tjo.space/mentos1386/zdravko/internal/workflows" + "go.temporal.io/sdk/client" + "go.temporal.io/sdk/temporal" + "gorm.io/gorm" +) + +func getScheduleId(monitor *models.Monitor, group string) string { + return "monitor-" + monitor.Slug + "-" + group +} + +func CreateMonitor(ctx context.Context, query *query.Query, monitor *models.Monitor) error { + return query.Monitor.WithContext(ctx).Create(monitor) +} + +func UpdateMonitor(ctx context.Context, q *query.Query, monitor *models.Monitor) error { + _, err := q.Monitor.WithContext(ctx).Where( + q.Monitor.Slug.Eq(monitor.Slug), + ).Updates(monitor) + return err +} + +func GetMonitor(ctx context.Context, q *query.Query, slug string) (*models.Monitor, error) { + return q.Monitor.WithContext(ctx).Where( + q.Monitor.Slug.Eq(slug), + q.Monitor.DeletedAt.IsNull(), + ).Preload( + q.Monitor.History, + ).First() +} + +func GetMonitors(ctx context.Context, q *query.Query) ([]*models.Monitor, error) { + return q.Monitor.WithContext(ctx).Preload( + q.Monitor.History, + ).Where( + q.Monitor.DeletedAt.IsNull(), + ).Find() +} + +func CreateOrUpdateMonitorSchedule(ctx context.Context, t client.Client, monitor *models.Monitor) error { + log.Println("Creating or Updating Monitor Schedule") + + args := make([]interface{}, 0) + args = append(args, workflows.MonitorWorkflowParam{Script: monitor.Script, Slug: monitor.Slug}) + + for _, group := range monitor.WorkerGroups { + options := client.ScheduleOptions{ + ID: getScheduleId(monitor, group), + //SearchAttributes: map[string]interface{}{ + // "worker-group": group, + // "monitor-slug": monitor.Slug, + //}, + Spec: client.ScheduleSpec{ + CronExpressions: []string{monitor.Schedule}, + Jitter: time.Second * 10, + }, + Action: &client.ScheduleWorkflowAction{ + ID: getScheduleId(monitor, group), + Workflow: workflows.NewWorkflows(nil).MonitorWorkflowDefinition, + Args: args, + TaskQueue: group, + RetryPolicy: &temporal.RetryPolicy{ + MaximumAttempts: 3, + }, + }, + } + + schedule := t.ScheduleClient().GetHandle(ctx, getScheduleId(monitor, group)) + + // If exists, we update + _, err := schedule.Describe(ctx) + if err == nil { + err = schedule.Update(ctx, client.ScheduleUpdateOptions{ + DoUpdate: func(input client.ScheduleUpdateInput) (*client.ScheduleUpdate, error) { + return &client.ScheduleUpdate{ + Schedule: &client.Schedule{ + Spec: &options.Spec, + Action: options.Action, + Policy: input.Description.Schedule.Policy, + State: input.Description.Schedule.State, + }, + }, nil + }, + }) + if err != nil { + return err + } + } else { + schedule, err = t.ScheduleClient().Create(ctx, options) + if err != nil { + return err + } + } + + err = schedule.Trigger(ctx, client.ScheduleTriggerOptions{}) + if err != nil { + return err + } + } + + return nil +} + +func CreateMonitorHistory(ctx context.Context, db *gorm.DB, monitorHistory *models.MonitorHistory) error { + return db.WithContext(ctx).Create(monitorHistory).Error +} diff --git a/internal/workflows/healthcheck.go b/internal/workflows/healthcheck.go deleted file mode 100644 index 43da0ed..0000000 --- a/internal/workflows/healthcheck.go +++ /dev/null @@ -1,50 +0,0 @@ -package workflows - -import ( - "time" - - "code.tjo.space/mentos1386/zdravko/internal/activities" - "code.tjo.space/mentos1386/zdravko/internal/models" - "go.temporal.io/sdk/workflow" -) - -type HealthcheckWorkflowParam struct { - Script string - Slug string -} - -func (w *Workflows) HealthcheckWorkflowDefinition(ctx workflow.Context, param HealthcheckWorkflowParam) error { - options := workflow.ActivityOptions{ - StartToCloseTimeout: 10 * time.Second, - } - ctx = workflow.WithActivityOptions(ctx, options) - - heatlcheckParam := activities.HealtcheckParam{ - Script: param.Script, - } - - var healthcheckResult *activities.HealthcheckResult - err := workflow.ExecuteActivity(ctx, w.activities.Healthcheck, heatlcheckParam).Get(ctx, &healthcheckResult) - if err != nil { - return err - } - - status := models.HealthcheckFailure - if healthcheckResult.Success { - status = models.HealthcheckSuccess - } - - historyParam := activities.HealtcheckAddToHistoryParam{ - Slug: param.Slug, - Status: status, - Note: healthcheckResult.Note, - } - - var historyResult *activities.HealthcheckAddToHistoryResult - err = workflow.ExecuteActivity(ctx, w.activities.HealthcheckAddToHistory, historyParam).Get(ctx, &historyResult) - if err != nil { - return err - } - - return nil -} diff --git a/internal/workflows/monitor.go b/internal/workflows/monitor.go new file mode 100644 index 0000000..ed02879 --- /dev/null +++ b/internal/workflows/monitor.go @@ -0,0 +1,50 @@ +package workflows + +import ( + "time" + + "code.tjo.space/mentos1386/zdravko/internal/activities" + "code.tjo.space/mentos1386/zdravko/internal/models" + "go.temporal.io/sdk/workflow" +) + +type MonitorWorkflowParam struct { + Script string + Slug string +} + +func (w *Workflows) MonitorWorkflowDefinition(ctx workflow.Context, param MonitorWorkflowParam) error { + options := workflow.ActivityOptions{ + StartToCloseTimeout: 10 * time.Second, + } + ctx = workflow.WithActivityOptions(ctx, options) + + heatlcheckParam := activities.HealtcheckParam{ + Script: param.Script, + } + + var monitorResult *activities.MonitorResult + err := workflow.ExecuteActivity(ctx, w.activities.Monitor, heatlcheckParam).Get(ctx, &monitorResult) + if err != nil { + return err + } + + status := models.MonitorFailure + if monitorResult.Success { + status = models.MonitorSuccess + } + + historyParam := activities.HealtcheckAddToHistoryParam{ + Slug: param.Slug, + Status: status, + Note: monitorResult.Note, + } + + var historyResult *activities.MonitorAddToHistoryResult + err = workflow.ExecuteActivity(ctx, w.activities.MonitorAddToHistory, historyParam).Get(ctx, &historyResult) + if err != nil { + return err + } + + return nil +} diff --git a/pkg/api/healthchecks.go b/pkg/api/monitors.go similarity index 61% rename from pkg/api/healthchecks.go rename to pkg/api/monitors.go index 696ec19..5696d6b 100644 --- a/pkg/api/healthchecks.go +++ b/pkg/api/monitors.go @@ -1,6 +1,6 @@ package api -type ApiV1HealthchecksHistoryPOSTBody struct { +type ApiV1MonitorsHistoryPOSTBody struct { Status string `json:"status"` Note string `json:"note"` } diff --git a/pkg/server/server.go b/pkg/server/server.go index 6b862f9..82eb56f 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -78,11 +78,11 @@ func (s *Server) Start() error { settings := s.echo.Group("/settings") settings.Use(h.Authenticated) settings.GET("", h.SettingsOverviewGET) - settings.GET("/healthchecks", h.SettingsHealthchecksGET) - settings.GET("/healthchecks/create", h.SettingsHealthchecksCreateGET) - settings.POST("/healthchecks/create", h.SettingsHealthchecksCreatePOST) - settings.GET("/healthchecks/:slug", h.SettingsHealthchecksDescribeGET) - settings.POST("/healthchecks/:slug", h.SettingsHealthchecksDescribePOST) + settings.GET("/monitors", h.SettingsMonitorsGET) + settings.GET("/monitors/create", h.SettingsMonitorsCreateGET) + settings.POST("/monitors/create", h.SettingsMonitorsCreatePOST) + settings.GET("/monitors/:slug", h.SettingsMonitorsDescribeGET) + settings.POST("/monitors/:slug", h.SettingsMonitorsDescribePOST) settings.GET("/workers", h.SettingsWorkersGET) settings.GET("/workers/create", h.SettingsWorkersCreateGET) settings.POST("/workers/create", h.SettingsWorkersCreatePOST) @@ -99,7 +99,7 @@ func (s *Server) Start() error { apiv1 := s.echo.Group("/api/v1") apiv1.Use(h.Authenticated) apiv1.GET("/workers/connect", h.ApiV1WorkersConnectGET) - apiv1.POST("/healthchecks/:slug/history", h.ApiV1HealthchecksHistoryPOST) + apiv1.POST("/monitors/:slug/history", h.ApiV1MonitorsHistoryPOST) // Error handler s.echo.HTTPErrorHandler = func(err error, c echo.Context) { diff --git a/pkg/worker/worker.go b/pkg/worker/worker.go index 7e2b1ef..4e31b96 100644 --- a/pkg/worker/worker.go +++ b/pkg/worker/worker.go @@ -94,11 +94,11 @@ func (w *Worker) Start() error { workerWorkflows := workflows.NewWorkflows(workerActivities) // Register Workflows - w.worker.RegisterWorkflow(workerWorkflows.HealthcheckWorkflowDefinition) + w.worker.RegisterWorkflow(workerWorkflows.MonitorWorkflowDefinition) // Register Activities - w.worker.RegisterActivity(workerActivities.Healthcheck) - w.worker.RegisterActivity(workerActivities.HealthcheckAddToHistory) + w.worker.RegisterActivity(workerActivities.Monitor) + w.worker.RegisterActivity(workerActivities.MonitorAddToHistory) return w.worker.Run(worker.InterruptCh()) } diff --git a/tools/generate/main.go b/tools/generate/main.go index 1ad952c..f42be45 100644 --- a/tools/generate/main.go +++ b/tools/generate/main.go @@ -30,8 +30,8 @@ func main() { // Generate default DAO interface for those specified structs g.ApplyBasic( models.Worker{}, - models.Healthcheck{}, - models.HealthcheckHistory{}, + models.Monitor{}, + models.MonitorHistory{}, models.Cronjob{}, models.CronjobHistory{}, models.OAuth2State{}, diff --git a/web/static/css/main.css b/web/static/css/main.css index e2bdf74..8d8d95c 100644 --- a/web/static/css/main.css +++ b/web/static/css/main.css @@ -56,23 +56,23 @@ code { @apply bg-blue-700 text-white; } -.healthchecks { +.monitors { @apply grid justify-items-stretch justify-stretch items-center mt-20 bg-white shadow-md p-5 rounded-lg; } -.healthchecks > div:not(:last-child) { +.monitors > div:not(:last-child) { @apply mb-3; } -.healthchecks .time-range > a { +.monitors .time-range > a { @apply font-medium text-sm px-2.5 py-1; @apply text-black bg-gray-100 hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-300; } -.healthchecks .time-range > a.active { +.monitors .time-range > a.active { @apply text-white bg-blue-700 hover:bg-blue-800; } -.healthchecks .time-range > a:first-child { +.monitors .time-range > a:first-child { @apply rounded-s-lg; } -.healthchecks .time-range > a:last-child { +.monitors .time-range > a:last-child { @apply rounded-e-lg; } diff --git a/web/static/css/tailwind.css b/web/static/css/tailwind.css index 9891ab8..7363074 100644 --- a/web/static/css/tailwind.css +++ b/web/static/css/tailwind.css @@ -1297,7 +1297,7 @@ code { color: rgb(255 255 255 / var(--tw-text-opacity)); } -.healthchecks { +.monitors { margin-top: 5rem; display: grid; align-items: center; @@ -1312,11 +1312,11 @@ code { box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } -.healthchecks > div:not(:last-child) { +.monitors > div:not(:last-child) { margin-bottom: 0.75rem; } -.healthchecks .time-range > a { +.monitors .time-range > a { padding-left: 0.625rem; padding-right: 0.625rem; padding-top: 0.25rem; @@ -1330,12 +1330,12 @@ code { color: rgb(0 0 0 / var(--tw-text-opacity)); } -.healthchecks .time-range > a:hover { +.monitors .time-range > a:hover { --tw-bg-opacity: 1; background-color: rgb(209 213 219 / var(--tw-bg-opacity)); } -.healthchecks .time-range > a:focus { +.monitors .time-range > a:focus { outline: 2px solid transparent; outline-offset: 2px; --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); @@ -1345,24 +1345,24 @@ code { --tw-ring-color: rgb(147 197 253 / var(--tw-ring-opacity)); } -.healthchecks .time-range > a.active { +.monitors .time-range > a.active { --tw-bg-opacity: 1; background-color: rgb(29 78 216 / var(--tw-bg-opacity)); --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } -.healthchecks .time-range > a.active:hover { +.monitors .time-range > a.active:hover { --tw-bg-opacity: 1; background-color: rgb(30 64 175 / var(--tw-bg-opacity)); } -.healthchecks .time-range > a:first-child { +.monitors .time-range > a:first-child { border-start-start-radius: 0.5rem; border-end-start-radius: 0.5rem; } -.healthchecks .time-range > a:last-child { +.monitors .time-range > a:last-child { border-start-end-radius: 0.5rem; border-end-end-radius: 0.5rem; } @@ -1610,10 +1610,6 @@ code { } @media (min-width: 768px) { - .md\:grid-cols-4 { - grid-template-columns: repeat(4, minmax(0, 1fr)); - } - .md\:px-40 { padding-left: 10rem; padding-right: 10rem; diff --git a/web/templates/pages/index.tmpl b/web/templates/pages/index.tmpl index b3d71ed..7100949 100644 --- a/web/templates/pages/index.tmpl +++ b/web/templates/pages/index.tmpl @@ -34,18 +34,18 @@ {{define "main"}}
- Create a healthcheck to monitor your services and get notified when they are down. + Create a monitor to monitor your services and get notified when they are down.
@@ -65,9 +65,9 @@Last updated on Feb 10 at 10:55am UTC
Healthchecks
+Monitors
{{ $description }}
@@ -21,12 +21,12 @@@@ -76,7 +76,7 @@ {{.Schedule}} | - Details + Details |
---|