wings/internal/cron/activity_cron.go

60 lines
1.6 KiB
Go
Raw Normal View History

package cron
import (
"context"
2022-10-05 23:24:11 +00:00
"emperror.dev/errors"
2022-10-06 15:58:42 +00:00
2022-07-24 15:43:48 +00:00
"github.com/pterodactyl/wings/internal/database"
"github.com/pterodactyl/wings/internal/models"
"github.com/pterodactyl/wings/server"
"github.com/pterodactyl/wings/system"
)
2022-07-10 20:51:11 +00:00
type activityCron struct {
mu *system.AtomicBool
manager *server.Manager
max int
2022-07-10 20:51:11 +00:00
}
// Run executes the cronjob and ensures we fetch and send all of the stored activity to the
// Panel instance. Once activity is sent it is deleted from the local database instance. Any
// SFTP specific events are not handled in this cron, they're handled seperately to account
// for de-duplication and event merging.
func (ac *activityCron) Run(ctx context.Context) error {
// Don't execute this cron if there is currently one running. Once this task is completed
// go ahead and mark it as no longer running.
2022-07-10 20:51:11 +00:00
if !ac.mu.SwapIf(true) {
return errors.WithStack(ErrCronRunning)
}
2022-07-10 20:51:11 +00:00
defer ac.mu.Store(false)
2022-07-24 15:43:48 +00:00
var activity []models.Activity
tx := database.Instance().WithContext(ctx).
Where("event NOT LIKE ?", "server:sftp.%").
Limit(ac.max).
2022-07-24 15:43:48 +00:00
Find(&activity)
2022-07-24 15:43:48 +00:00
if tx.Error != nil {
return errors.WithStack(tx.Error)
2022-07-10 20:51:11 +00:00
}
2022-07-24 15:43:48 +00:00
if len(activity) == 0 {
2022-07-10 20:51:11 +00:00
return nil
}
2022-07-24 15:43:48 +00:00
if err := ac.manager.Client().SendActivityLogs(ctx, activity); err != nil {
return errors.WrapIf(err, "cron: failed to send activity events to Panel")
}
2022-07-24 15:43:48 +00:00
var ids []int
for _, v := range activity {
ids = append(ids, v.ID)
}
tx = database.Instance().WithContext(ctx).Where("id IN ?", ids).Delete(&models.Activity{})
if tx.Error != nil {
return errors.WithStack(tx.Error)
2022-07-10 20:51:11 +00:00
}
2022-07-24 15:43:48 +00:00
return nil
}