2022-04-05 16:56:15 +00:00
|
|
|
package mysql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2023-05-03 20:25:36 +00:00
|
|
|
"time"
|
2022-04-05 16:56:15 +00:00
|
|
|
|
|
|
|
"github.com/fleetdm/fleet/v4/server/fleet"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (ds *Datastore) NewJob(ctx context.Context, job *fleet.Job) (*fleet.Job, error) {
|
|
|
|
query := `
|
|
|
|
INSERT INTO jobs (
|
|
|
|
name,
|
|
|
|
args,
|
|
|
|
state,
|
|
|
|
retries,
|
2023-05-03 20:25:36 +00:00
|
|
|
error,
|
|
|
|
not_before
|
2022-04-05 16:56:15 +00:00
|
|
|
)
|
2023-05-03 20:25:36 +00:00
|
|
|
VALUES (?, ?, ?, ?, ?, COALESCE(?, NOW()))
|
2022-04-05 16:56:15 +00:00
|
|
|
`
|
2023-05-03 20:25:36 +00:00
|
|
|
var notBefore *time.Time
|
|
|
|
if !job.NotBefore.IsZero() {
|
|
|
|
notBefore = &job.NotBefore
|
|
|
|
}
|
2023-06-19 17:55:15 +00:00
|
|
|
result, err := ds.writer(ctx).ExecContext(ctx, query, job.Name, job.Args, job.State, job.Retries, job.Error, notBefore)
|
2022-04-05 16:56:15 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
id, _ := result.LastInsertId()
|
|
|
|
job.ID = uint(id)
|
|
|
|
|
|
|
|
return job, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ds *Datastore) GetQueuedJobs(ctx context.Context, maxNumJobs int) ([]*fleet.Job, error) {
|
|
|
|
query := `
|
|
|
|
SELECT
|
2023-05-03 20:25:36 +00:00
|
|
|
id, created_at, updated_at, name, args, state, retries, error, not_before
|
2022-04-05 16:56:15 +00:00
|
|
|
FROM
|
|
|
|
jobs
|
|
|
|
WHERE
|
2023-05-03 20:25:36 +00:00
|
|
|
state = ? AND
|
|
|
|
not_before <= NOW()
|
2022-04-05 16:56:15 +00:00
|
|
|
ORDER BY
|
2022-04-11 20:42:16 +00:00
|
|
|
updated_at ASC
|
2022-04-05 16:56:15 +00:00
|
|
|
LIMIT ?
|
|
|
|
`
|
|
|
|
|
|
|
|
var jobs []*fleet.Job
|
2023-06-19 17:55:15 +00:00
|
|
|
err := sqlx.SelectContext(ctx, ds.reader(ctx), &jobs, query, fleet.JobStateQueued, maxNumJobs)
|
2022-04-05 16:56:15 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return jobs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ds *Datastore) UpdateJob(ctx context.Context, id uint, job *fleet.Job) (*fleet.Job, error) {
|
|
|
|
query := `
|
|
|
|
UPDATE jobs
|
|
|
|
SET
|
|
|
|
state = ?,
|
|
|
|
retries = ?,
|
2023-05-03 20:25:36 +00:00
|
|
|
error = ?,
|
|
|
|
not_before = COALESCE(?, NOW())
|
2022-04-05 16:56:15 +00:00
|
|
|
WHERE
|
|
|
|
id = ?
|
|
|
|
`
|
2023-05-03 20:25:36 +00:00
|
|
|
var notBefore *time.Time
|
|
|
|
if !job.NotBefore.IsZero() {
|
|
|
|
notBefore = &job.NotBefore
|
|
|
|
}
|
2023-06-19 17:55:15 +00:00
|
|
|
_, err := ds.writer(ctx).ExecContext(ctx, query, job.State, job.Retries, job.Error, notBefore, id)
|
2022-04-05 16:56:15 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return job, nil
|
|
|
|
}
|