Skip to content

Commit

Permalink
all: migrate executed command logging to sqlboiler
Browse files Browse the repository at this point in the history
  • Loading branch information
jo3-l committed May 25, 2024
1 parent 37287cf commit 6471f82
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 47 deletions.
4 changes: 0 additions & 4 deletions commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,6 @@ func (p *Plugin) PluginInfo() *common.PluginInfo {
func RegisterPlugin() {
plugin := &Plugin{}
common.RegisterPlugin(plugin)
err := common.GORM.AutoMigrate(&common.LoggedExecutedCommand{}).Error
if err != nil {
logger.WithError(err).Fatal("Failed migrating logged commands database")
}

common.InitSchemas("commands", DBSchemas...)
}
Expand Down
10 changes: 6 additions & 4 deletions commands/yagcommmand.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/sirupsen/logrus"
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/volatiletech/sqlboiler/v4/queries/qm"

commonmodels "github.com/botlabs-gg/yagpdb/v2/common/models"
)

type ContextKey int
Expand Down Expand Up @@ -233,7 +236,7 @@ func (yc *YAGCommand) Run(data *dcmd.Data) (interface{}, error) {
}

// Set up log entry for later use
logEntry := &common.LoggedExecutedCommand{
logEntry := &commonmodels.ExecutedCommand{
UserID: discordgo.StrID(data.Author.ID),
ChannelID: discordgo.StrID(data.ChannelID),

Expand All @@ -243,8 +246,7 @@ func (yc *YAGCommand) Run(data *dcmd.Data) (interface{}, error) {
}

if data.GuildData != nil {
logEntry.GuildID = discordgo.StrID(data.GuildData.GS.ID)

logEntry.GuildID.SetValid(discordgo.StrID(data.GuildData.GS.ID))
}

metricsExcecutedCommands.With(prometheus.Labels{"name": "(other)", "trigger_type": triggerType}).Inc()
Expand Down Expand Up @@ -284,7 +286,7 @@ func (yc *YAGCommand) Run(data *dcmd.Data) (interface{}, error) {
}

// Create command log entry
err := common.GORM.Create(logEntry).Error
err := logEntry.InsertG(data.Context(), boil.Infer())
if err != nil {
logger.WithError(err).Error("Failed creating command execution log")
}
Expand Down
4 changes: 4 additions & 0 deletions common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ func Init() error {

logger.Info("Initializing core schema")
InitSchemas("core_configs", CoreServerConfDBSchema, localIDsSchema)

logger.Info("Initializing executed command log schema")
InitSchemas("executed_commands", ExecutedCommandDBSchemas...)

initQueuedSchemas()

return err
Expand Down
22 changes: 0 additions & 22 deletions common/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,28 +354,6 @@ func IsDiscordErr(err error, codes ...int) bool {
return false
}

type LoggedExecutedCommand struct {
SmallModel

UserID string
ChannelID string
GuildID string

// Name of command that was triggered
Command string
// Raw command with arguments passed
RawCommand string
// If command returned any error this will be no-empty
Error string

TimeStamp time.Time
ResponseTime int64
}

func (l LoggedExecutedCommand) TableName() string {
return "executed_commands"
}

func HumanizePermissions(perms int64) (res []string) {
if perms&discordgo.PermissionAdministrator == discordgo.PermissionAdministrator {
res = append(res, "Administrator")
Expand Down
29 changes: 19 additions & 10 deletions stdcommands/topcommands/topcommands.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,31 @@ func cmdFuncTopCommands(data *dcmd.Data) (interface{}, error) {
hours := data.Args[0].Int()
within := time.Now().Add(time.Duration(-hours) * time.Hour)

var results []*TopCommandsResult
err := common.GORM.Table(common.LoggedExecutedCommand{}.TableName()).Select("command, COUNT(id)").Where("created_at > ?", within).Group("command").Order("count(id) desc").Scan(&results).Error
const q = `
SELECT command, COUNT(id)
FROM executed_commands
WHERE created_at > $1
GROUP BY command
ORDER BY COUNT(id) DESC;
`
rows, err := common.PQ.Query(q, within)
if err != nil {
return nil, err
}
defer rows.Close()

out := fmt.Sprintf("```\nCommand stats from now to %d hour(s) ago\n# Total - Command\n", hours)
total := 0
for k, result := range results {
out += fmt.Sprintf("#%02d: %5d - %s\n", k+1, result.Count, result.Command)
total += result.Count
for k := 1; rows.Next(); k++ {
var command string
var count int
err = rows.Scan(&command, &count)
if err != nil {
return nil, err
}

out += fmt.Sprintf("#%02d: %5d - %s\n", k, count, command)
total += count
}

cpm := float64(total) / float64(hours) / 60
Expand All @@ -46,8 +60,3 @@ func cmdFuncTopCommands(data *dcmd.Data) (interface{}, error) {

return out, nil
}

type TopCommandsResult struct {
Command string
Count int
}
9 changes: 2 additions & 7 deletions web/handlers_general.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,17 +386,12 @@ var commandsRanToday = new(int64)
func pollCommandsRan() {
t := time.NewTicker(time.Minute)
for {
var result struct {
Count int64
}

within := time.Now().Add(-24 * time.Hour)

err := common.GORM.Table(common.LoggedExecutedCommand{}.TableName()).Select("COUNT(*)").Where("created_at > ?", within).Scan(&result).Error
count, err := models.ExecutedCommands(models.ExecutedCommandWhere.CreatedAt.GT(within)).CountG(context.Background())
if err != nil {
logger.WithError(err).Error("failed counting commands ran today")
} else {
atomic.StoreInt64(commandsRanToday, result.Count)
atomic.StoreInt64(commandsRanToday, count)
}

<-t.C
Expand Down

0 comments on commit 6471f82

Please sign in to comment.