diff --git a/cli/cron/cron.go b/cli/cron/cron.go new file mode 100644 index 000000000..bab540c1e --- /dev/null +++ b/cli/cron/cron.go @@ -0,0 +1,21 @@ +package cron + +import ( + "github.com/urfave/cli/v2" + + "github.com/woodpecker-ci/woodpecker/cli/common" +) + +// Command exports the cron command set. +var Command = &cli.Command{ + Name: "cron", + Usage: "manage cron jobs", + Flags: common.GlobalFlags, + Subcommands: []*cli.Command{ + cronCreateCmd, + cronDeleteCmd, + cronUpdateCmd, + cronInfoCmd, + cronListCmd, + }, +} diff --git a/cli/cron/cron_add.go b/cli/cron/cron_add.go new file mode 100644 index 000000000..59bab6b56 --- /dev/null +++ b/cli/cron/cron_add.go @@ -0,0 +1,72 @@ +package cron + +import ( + "html/template" + "os" + + "github.com/urfave/cli/v2" + + "github.com/woodpecker-ci/woodpecker/cli/common" + "github.com/woodpecker-ci/woodpecker/cli/internal" + "github.com/woodpecker-ci/woodpecker/woodpecker-go/woodpecker" +) + +var cronCreateCmd = &cli.Command{ + Name: "add", + Usage: "adds a cron", + ArgsUsage: "[repo/name]", + Action: cronCreate, + Flags: append(common.GlobalFlags, + common.RepoFlag, + &cli.StringFlag{ + Name: "name", + Usage: "cron name", + Required: true, + }, + &cli.StringFlag{ + Name: "branch", + Usage: "cron branch", + }, + &cli.StringFlag{ + Name: "schedule", + Usage: "cron schedule", + Required: true, + }, + common.FormatFlag(tmplCronList, true), + ), +} + +func cronCreate(c *cli.Context) error { + var ( + jobName = c.String("name") + branch = c.String("branch") + schedule = c.String("schedule") + reponame = c.String("repository") + format = c.String("format") + "\n" + ) + if reponame == "" { + reponame = c.Args().First() + } + owner, name, err := internal.ParseRepo(reponame) + if err != nil { + return err + } + client, err := internal.NewClient(c) + if err != nil { + return err + } + cron := &woodpecker.Cron{ + Name: jobName, + Branch: branch, + Schedule: schedule, + } + cron, err = client.CronCreate(owner, name, cron) + if err != nil { + return err + } + tmpl, err := template.New("_").Parse(format) + if err != nil { + return err + } + return tmpl.Execute(os.Stdout, cron) +} diff --git a/cli/cron/cron_info.go b/cli/cron/cron_info.go new file mode 100644 index 000000000..3ed67ab68 --- /dev/null +++ b/cli/cron/cron_info.go @@ -0,0 +1,55 @@ +package cron + +import ( + "html/template" + "os" + + "github.com/urfave/cli/v2" + + "github.com/woodpecker-ci/woodpecker/cli/common" + "github.com/woodpecker-ci/woodpecker/cli/internal" +) + +var cronInfoCmd = &cli.Command{ + Name: "info", + Usage: "display cron info", + ArgsUsage: "[repo/name]", + Action: cronInfo, + Flags: append(common.GlobalFlags, + common.RepoFlag, + &cli.StringFlag{ + Name: "id", + Usage: "cron id", + Required: true, + }, + common.FormatFlag(tmplCronList, true), + ), +} + +func cronInfo(c *cli.Context) error { + var ( + jobID = c.Int64("id") + reponame = c.String("repository") + format = c.String("format") + "\n" + ) + if reponame == "" { + reponame = c.Args().First() + } + owner, name, err := internal.ParseRepo(reponame) + if err != nil { + return err + } + client, err := internal.NewClient(c) + if err != nil { + return err + } + cron, err := client.CronGet(owner, name, jobID) + if err != nil { + return err + } + tmpl, err := template.New("_").Parse(format) + if err != nil { + return err + } + return tmpl.Execute(os.Stdout, cron) +} diff --git a/cli/cron/cron_list.go b/cli/cron/cron_list.go new file mode 100644 index 000000000..d7e2b8880 --- /dev/null +++ b/cli/cron/cron_list.go @@ -0,0 +1,62 @@ +package cron + +import ( + "html/template" + "os" + + "github.com/urfave/cli/v2" + + "github.com/woodpecker-ci/woodpecker/cli/common" + "github.com/woodpecker-ci/woodpecker/cli/internal" +) + +var cronListCmd = &cli.Command{ + Name: "ls", + Usage: "list registries", + ArgsUsage: "[repo/name]", + Action: cronList, + Flags: append(common.GlobalFlags, + common.RepoFlag, + common.FormatFlag(tmplCronList, true), + ), +} + +func cronList(c *cli.Context) error { + var ( + format = c.String("format") + "\n" + reponame = c.String("repository") + ) + if reponame == "" { + reponame = c.Args().First() + } + owner, name, err := internal.ParseRepo(reponame) + if err != nil { + return err + } + client, err := internal.NewClient(c) + if err != nil { + return err + } + list, err := client.CronList(owner, name) + if err != nil { + return err + } + tmpl, err := template.New("_").Parse(format) + if err != nil { + return err + } + for _, cron := range list { + if err := tmpl.Execute(os.Stdout, cron); err != nil { + return err + } + } + return nil +} + +// template for build list information +var tmplCronList = "\x1b[33m{{ .Name }} \x1b[0m" + ` +ID: {{ .ID }} +Branch: {{ .Branch }} +Schedule: {{ .Schedule }} +NextExec: {{ .NextExec }} +` diff --git a/cli/cron/cron_rm.go b/cli/cron/cron_rm.go new file mode 100644 index 000000000..bf468785b --- /dev/null +++ b/cli/cron/cron_rm.go @@ -0,0 +1,50 @@ +package cron + +import ( + "fmt" + + "github.com/urfave/cli/v2" + + "github.com/woodpecker-ci/woodpecker/cli/common" + "github.com/woodpecker-ci/woodpecker/cli/internal" +) + +var cronDeleteCmd = &cli.Command{ + Name: "rm", + Usage: "remove a cron", + ArgsUsage: "[repo/name]", + Action: cronDelete, + Flags: append(common.GlobalFlags, + common.RepoFlag, + &cli.StringFlag{ + Name: "id", + Usage: "cron id", + Required: true, + }, + ), +} + +func cronDelete(c *cli.Context) error { + var ( + jobID = c.Int64("id") + reponame = c.String("repository") + ) + if reponame == "" { + reponame = c.Args().First() + } + owner, name, err := internal.ParseRepo(reponame) + if err != nil { + return err + } + client, err := internal.NewClient(c) + if err != nil { + return err + } + err = client.CronDelete(owner, name, jobID) + if err != nil { + return err + } + + fmt.Println("Success") + return nil +} diff --git a/cli/cron/cron_update.go b/cli/cron/cron_update.go new file mode 100644 index 000000000..fefff774d --- /dev/null +++ b/cli/cron/cron_update.go @@ -0,0 +1,77 @@ +package cron + +import ( + "html/template" + "os" + + "github.com/urfave/cli/v2" + + "github.com/woodpecker-ci/woodpecker/cli/common" + "github.com/woodpecker-ci/woodpecker/cli/internal" + "github.com/woodpecker-ci/woodpecker/woodpecker-go/woodpecker" +) + +var cronUpdateCmd = &cli.Command{ + Name: "update", + Usage: "update a cron", + ArgsUsage: "[repo/name]", + Action: cronUpdate, + Flags: append(common.GlobalFlags, + common.RepoFlag, + &cli.StringFlag{ + Name: "id", + Usage: "cron id", + Required: true, + }, + &cli.StringFlag{ + Name: "name", + Usage: "cron name", + }, + &cli.StringFlag{ + Name: "branch", + Usage: "cron branch", + }, + &cli.StringFlag{ + Name: "schedule", + Usage: "cron schedule", + }, + common.FormatFlag(tmplCronList, true), + ), +} + +func cronUpdate(c *cli.Context) error { + var ( + reponame = c.String("repository") + jobID = c.Int64("id") + jobName = c.String("name") + branch = c.String("branch") + schedule = c.String("schedule") + format = c.String("format") + "\n" + ) + if reponame == "" { + reponame = c.Args().First() + } + owner, name, err := internal.ParseRepo(reponame) + if err != nil { + return err + } + client, err := internal.NewClient(c) + if err != nil { + return err + } + cron := &woodpecker.Cron{ + ID: jobID, + Name: jobName, + Branch: branch, + Schedule: schedule, + } + cron, err = client.CronUpdate(owner, name, cron) + if err != nil { + return err + } + tmpl, err := template.New("_").Parse(format) + if err != nil { + return err + } + return tmpl.Execute(os.Stdout, cron) +} diff --git a/cli/secret/secret_add.go b/cli/secret/secret_add.go index 2a368fcf3..7b0f53afb 100644 --- a/cli/secret/secret_add.go +++ b/cli/secret/secret_add.go @@ -25,10 +25,7 @@ var secretCreateCmd = &cli.Command{ Name: "organization", Usage: "organization name (e.g. octocat)", }, - &cli.StringFlag{ - Name: "repository", - Usage: "repository name (e.g. octocat/hello-world)", - }, + common.RepoFlag, &cli.StringFlag{ Name: "name", Usage: "secret name", diff --git a/cli/secret/secret_info.go b/cli/secret/secret_info.go index c4fe2969b..26e9b4281 100644 --- a/cli/secret/secret_info.go +++ b/cli/secret/secret_info.go @@ -25,10 +25,7 @@ var secretInfoCmd = &cli.Command{ Name: "organization", Usage: "organization name (e.g. octocat)", }, - &cli.StringFlag{ - Name: "repository", - Usage: "repository name (e.g. octocat/hello-world)", - }, + common.RepoFlag, &cli.StringFlag{ Name: "name", Usage: "secret name", diff --git a/cli/secret/secret_list.go b/cli/secret/secret_list.go index a2f43efd2..e167ed99e 100644 --- a/cli/secret/secret_list.go +++ b/cli/secret/secret_list.go @@ -26,10 +26,7 @@ var secretListCmd = &cli.Command{ Name: "organization", Usage: "organization name (e.g. octocat)", }, - &cli.StringFlag{ - Name: "repository", - Usage: "repository name (e.g. octocat/hello-world)", - }, + common.RepoFlag, common.FormatFlag(tmplSecretList, true), ), } diff --git a/cli/secret/secret_rm.go b/cli/secret/secret_rm.go index f0046e3bd..a4fc25c67 100644 --- a/cli/secret/secret_rm.go +++ b/cli/secret/secret_rm.go @@ -21,10 +21,7 @@ var secretDeleteCmd = &cli.Command{ Name: "organization", Usage: "organization name (e.g. octocat)", }, - &cli.StringFlag{ - Name: "repository", - Usage: "repository name (e.g. octocat/hello-world)", - }, + common.RepoFlag, &cli.StringFlag{ Name: "name", Usage: "secret name", diff --git a/cli/secret/secret_set.go b/cli/secret/secret_set.go index 880a0c634..8449604ef 100644 --- a/cli/secret/secret_set.go +++ b/cli/secret/secret_set.go @@ -25,10 +25,7 @@ var secretUpdateCmd = &cli.Command{ Name: "organization", Usage: "organization name (e.g. octocat)", }, - &cli.StringFlag{ - Name: "repository", - Usage: "repository name (e.g. octocat/hello-world)", - }, + common.RepoFlag, &cli.StringFlag{ Name: "name", Usage: "secret name", diff --git a/cmd/cli/app.go b/cmd/cli/app.go index 2cca06deb..fa80efb1a 100644 --- a/cmd/cli/app.go +++ b/cmd/cli/app.go @@ -23,6 +23,7 @@ import ( "github.com/woodpecker-ci/woodpecker/cli/build" "github.com/woodpecker-ci/woodpecker/cli/common" + "github.com/woodpecker-ci/woodpecker/cli/cron" "github.com/woodpecker-ci/woodpecker/cli/deploy" "github.com/woodpecker-ci/woodpecker/cli/exec" "github.com/woodpecker-ci/woodpecker/cli/info" @@ -56,6 +57,7 @@ func newApp() *cli.App { user.Command, lint.Command, loglevel.Command, + cron.Command, } zlog.Logger = zlog.Output( diff --git a/cmd/server/server.go b/cmd/server/server.go index 12fb87dad..fc15a9fb7 100644 --- a/cmd/server/server.go +++ b/cmd/server/server.go @@ -39,6 +39,7 @@ import ( "github.com/woodpecker-ci/woodpecker/pipeline/rpc/proto" "github.com/woodpecker-ci/woodpecker/server" + "github.com/woodpecker-ci/woodpecker/server/cron" woodpeckerGrpcServer "github.com/woodpecker-ci/woodpecker/server/grpc" "github.com/woodpecker-ci/woodpecker/server/logging" "github.com/woodpecker-ci/woodpecker/server/model" @@ -185,6 +186,10 @@ func run(c *cli.Context) error { setupMetrics(&g, _store) + g.Go(func() error { + return cron.Start(c.Context, _store) + }) + // start the server with tls enabled if c.String("server-cert") != "" { g.Go(func() error { diff --git a/docs/docs/20-usage/20-pipeline-syntax.md b/docs/docs/20-usage/20-pipeline-syntax.md index 23773c5c8..c1978424c 100644 --- a/docs/docs/20-usage/20-pipeline-syntax.md +++ b/docs/docs/20-usage/20-pipeline-syntax.md @@ -341,10 +341,10 @@ when: :::info **By default steps are filtered by following event types:** -`push`, `pull_request, `tag`, `deployment`. +`push`, `pull_request`, `tag`, `deployment`. ::: -Available events: `push`, `pull_request`, `tag`, `deployment` +Available events: `push`, `pull_request`, `tag`, `deployment`, `cron` Execute a step if the build event is a `tag`: @@ -368,6 +368,20 @@ when: - event: [push, tag, deployment] ``` +#### `cron` + +This filter **only** applies to cron events and filters based on the name of a cron job. + +Make sure to have a `event: cron` condition in the `when`-filters as well. + +```yaml +when: + - event: cron + cron: sync_* # name of your cron job +``` + +[Read more about cron](/docs/usage/cron) + #### `tag` This filter only applies to tag events. diff --git a/docs/docs/20-usage/45-cron.md b/docs/docs/20-usage/45-cron.md new file mode 100644 index 000000000..064137979 --- /dev/null +++ b/docs/docs/20-usage/45-cron.md @@ -0,0 +1,39 @@ +# Cron + +To configure cron jobs you need at least push access to the repository. + +:::warning +By default pipelines triggered by cron jobs wont execute any steps in pipelines, as they are not part of the default event filter and you explicitly need to set a `event: cron` filter. +Read more at: [pipeline-syntax#event](/docs/usage/pipeline-syntax#event) +::: + +## Add a new cron job + +1. To create a new cron job adjust your pipeline config(s) and add the event filter to all steps you would like to run by the cron job: + + ```diff + pipeline: + sync_locales: + image: weblate_sync + settings: + url: example.com + token: + from_secret: weblate_token + + when: + + event: cron + + cron: "name of the cron job" # if you only want to execute this step by a specific cron job + ``` + +1. Create a new cron job in the repository settings: + + ![cron settings](./cron-settings.png) + + The supported schedule syntax can be found at . If you need general understanding of the cron syntax is a good place to start and experiment. + + Examples: `@every 5m`, `@daily`, `0 30 * * * *` ... + + :::info + Woodpeckers cron syntax starts with seconds instead of minutes as used by most linux cron schedulers. + + Example: "At minute 30 every hour" would be `0 30 * * * *` instead of `30 * * * *` + ::: diff --git a/docs/docs/20-usage/cron-settings.png b/docs/docs/20-usage/cron-settings.png new file mode 100644 index 000000000..d11c507af Binary files /dev/null and b/docs/docs/20-usage/cron-settings.png differ diff --git a/go.mod b/go.mod index f6ae1d103..cc7753c52 100644 --- a/go.mod +++ b/go.mod @@ -29,6 +29,7 @@ require ( github.com/mrjones/oauth v0.0.0-20190623134757-126b35219450 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.13.0 + github.com/robfig/cron v1.2.0 github.com/rs/zerolog v1.27.0 github.com/stretchr/testify v1.8.0 github.com/tevino/abool v1.2.0 diff --git a/go.sum b/go.sum index a31f65475..542c6ac2f 100644 --- a/go.sum +++ b/go.sum @@ -554,6 +554,8 @@ github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0ua github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ= +github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= diff --git a/pipeline/frontend/metadata.go b/pipeline/frontend/metadata.go index 6601c066c..b7c826e73 100644 --- a/pipeline/frontend/metadata.go +++ b/pipeline/frontend/metadata.go @@ -14,6 +14,7 @@ const ( EventPull = "pull_request" EventTag = "tag" EventDeploy = "deployment" + EventCron = "cron" ) type ( @@ -51,6 +52,7 @@ type ( Trusted bool `json:"trusted,omitempty"` Commit Commit `json:"commit,omitempty"` Parent int64 `json:"parent,omitempty"` + Cron string `json:"cron,omitempty"` } // Commit defines runtime metadata for a commit. diff --git a/pipeline/frontend/yaml/constraint/constraint.go b/pipeline/frontend/yaml/constraint/constraint.go index 45948c6ff..757945c43 100644 --- a/pipeline/frontend/yaml/constraint/constraint.go +++ b/pipeline/frontend/yaml/constraint/constraint.go @@ -26,6 +26,7 @@ type ( Environment List Event List Branch List + Cron List Status List Matrix Map Local types.BoolTrue @@ -153,6 +154,10 @@ func (c *Constraint) Match(metadata frontend.Metadata) bool { match = match && c.Branch.Match(metadata.Curr.Commit.Branch) } + if metadata.Curr.Event == frontend.EventCron { + match = match && c.Cron.Match(metadata.Curr.Cron) + } + return match } diff --git a/pipeline/frontend/yaml/constraint/constraint_test.go b/pipeline/frontend/yaml/constraint/constraint_test.go index 1a48f37a4..e822638a9 100644 --- a/pipeline/frontend/yaml/constraint/constraint_test.go +++ b/pipeline/frontend/yaml/constraint/constraint_test.go @@ -459,7 +459,25 @@ func TestConstraints(t *testing.T) { want: false, }, { - desc: "no constraints, and event get filtered by default default event filter", + desc: "filter cron by default constraint", + conf: "{}", + with: frontend.Metadata{Curr: frontend.Build{Event: frontend.EventCron}}, + want: false, + }, + { + desc: "filter cron by matching name", + conf: "{ event: cron, cron: job1 }", + with: frontend.Metadata{Curr: frontend.Build{Event: frontend.EventCron, Cron: "job1"}}, + want: true, + }, + { + desc: "filter cron by name", + conf: "{ event: cron, cron: job2 }", + with: frontend.Metadata{Curr: frontend.Build{Event: frontend.EventCron, Cron: "job1"}}, + want: false, + }, + { + desc: "no constraints, event gets filtered by default event filter", conf: "", with: frontend.Metadata{ Curr: frontend.Build{Event: "non-default"}, @@ -467,6 +485,7 @@ func TestConstraints(t *testing.T) { want: false, }, } + for _, test := range testdata { t.Run(test.desc, func(t *testing.T) { c := parseConstraints(t, test.conf) diff --git a/pipeline/frontend/yaml/container_test.go b/pipeline/frontend/yaml/container_test.go index 85fe82cc1..da7c67f78 100644 --- a/pipeline/frontend/yaml/container_test.go +++ b/pipeline/frontend/yaml/container_test.go @@ -58,7 +58,9 @@ volumes: tmpfs: - /var/lib/test when: - branch: master + - branch: master + - event: cron + cron: job1 settings: foo: bar baz: false @@ -116,6 +118,14 @@ func TestUnmarshalContainer(t *testing.T) { Include: []string{"master"}, }, }, + { + Event: constraint.List{ + Include: []string{"cron"}, + }, + Cron: constraint.List{ + Include: []string{"job1"}, + }, + }, }, }, Settings: map[string]interface{}{ diff --git a/pipeline/schema/.woodpecker/test-when.yml b/pipeline/schema/.woodpecker/test-when.yml index 83f1a87ac..d0159b6c5 100644 --- a/pipeline/schema/.woodpecker/test-when.yml +++ b/pipeline/schema/.woodpecker/test-when.yml @@ -121,3 +121,22 @@ pipeline: repo: test/test - event: push branch: main + + when-cron: + image: alpine + commands: + - echo "test" + when: + cron: "update locales" + event: cron + + when-cron-list: + image: alpine + commands: echo "test" + when: + event: cron + cron: + include: + - test + - hello + exclude: hi diff --git a/pipeline/schema/schema.json b/pipeline/schema/schema.json index 259e68189..94a54c2fa 100644 --- a/pipeline/schema/schema.json +++ b/pipeline/schema/schema.json @@ -157,29 +157,11 @@ "properties": { "repo": { "description": "Execute a step only on a specific repository. Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#repo", - "oneOf": [ - { - "type": "array", - "items": { - "type": "string" - }, - "minLength": 1 - }, - { "type": "string" } - ] + "$ref": "#/definitions/constraint_list" }, "branch": { "description": "Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#branch", - "oneOf": [ - { - "type": "array", - "items": { - "type": "string" - }, - "minLength": 1 - }, - { "type": "string" } - ] + "$ref": "#/definitions/constraint_list" }, "event": { "description": "Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#event", @@ -198,29 +180,31 @@ "description": "Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#tag", "type": "string" }, + "cron": { + "description": "filter cron by title. Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#cron", + "$ref": "#/definitions/constraint_list" + }, "status": { "description": "Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#status", - "type": "array", - "items": { - "enum": ["success", "failure"] - } - }, - "platform": { - "description": "Execute a step only on a specific platform. Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#platform", "oneOf": [ { "type": "array", - "items": { - "type": "string" - }, - "minLength": 1 + "minLength": 1, + "items": { "type": "string", "enum": ["success", "failure"] } }, - { "type": "string" } + { + "type": "string", + "enum": ["success", "failure"] + } ] }, + "platform": { + "description": "Execute a step only on a specific platform. Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#platform", + "$ref": "#/definitions/constraint_list" + }, "environment": { "description": "Execute a step only for a specific environment. Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#environment", - "type": "string" + "$ref": "#/definitions/constraint_list" }, "matrix": { "description": "Read more: https://woodpecker-ci.org/docs/usage/matrix-pipelines", @@ -231,7 +215,7 @@ }, "instance": { "description": "Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#instance", - "type": "string" + "$ref": "#/definitions/constraint_list" }, "path": { "description": "Execute a step only on commit with certain files added/removed/modified. Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#path", @@ -270,7 +254,49 @@ }, "event_enum": { "default": ["push", "pull_request", "tag", "deployment"], - "enum": ["push", "pull_request", "tag", "deployment"] + "enum": ["push", "pull_request", "tag", "deployment", "cron"] + }, + "constraint_list": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "minLength": 1, + "items": { "type": "string" } + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "include": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "minLength": 1, + "items": { "type": "string" } + } + ] + }, + "exclude": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "minLength": 1, + "items": { "type": "string" } + } + ] + } + } + } + ] }, "step_image": { "description": "Read more: https://woodpecker-ci.org/docs/usage/pipeline-syntax#image", diff --git a/server/api/cron.go b/server/api/cron.go new file mode 100644 index 000000000..714bda4a4 --- /dev/null +++ b/server/api/cron.go @@ -0,0 +1,179 @@ +// Copyright 2022 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package api + +import ( + "net/http" + "strconv" + "time" + + "github.com/gin-gonic/gin" + "github.com/woodpecker-ci/woodpecker/server" + cronScheduler "github.com/woodpecker-ci/woodpecker/server/cron" + "github.com/woodpecker-ci/woodpecker/server/model" + "github.com/woodpecker-ci/woodpecker/server/router/middleware/session" + "github.com/woodpecker-ci/woodpecker/server/store" +) + +// GetCron gets a cron job by id from the database and writes +// to the response in json format. +func GetCron(c *gin.Context) { + repo := session.Repo(c) + id, err := strconv.ParseInt(c.Param("cron"), 10, 64) + if err != nil { + c.String(400, "Error parsing cron id. %s", err) + return + } + + cron, err := store.FromContext(c).CronFind(repo, id) + if err != nil { + c.String(404, "Error getting cron %q. %s", id, err) + return + } + c.JSON(200, cron) +} + +// PostCron persists the cron job to the database. +func PostCron(c *gin.Context) { + repo := session.Repo(c) + user := session.User(c) + store := store.FromContext(c) + remote := server.Config.Services.Remote + + in := new(model.Cron) + if err := c.Bind(in); err != nil { + c.String(http.StatusBadRequest, "Error parsing request. %s", err) + return + } + cron := &model.Cron{ + RepoID: repo.ID, + Name: in.Name, + CreatorID: user.ID, + Schedule: in.Schedule, + Branch: in.Branch, + } + if err := cron.Validate(); err != nil { + c.String(400, "Error inserting cron. validate failed: %s", err) + return + } + + nextExec, err := cronScheduler.CalcNewNext(in.Schedule, time.Now()) + if err != nil { + c.String(400, "Error inserting cron. schedule could not parsed: %s", err) + return + } + cron.NextExec = nextExec.Unix() + + if in.Branch != "" { + // check if branch exists on remote + _, err := remote.BranchHead(c, user, repo, in.Branch) + if err != nil { + c.String(400, "Error inserting cron. branch not resolved: %s", err) + return + } + } + + if err := store.CronCreate(cron); err != nil { + c.String(500, "Error inserting cron %q. %s", in.Name, err) + return + } + c.JSON(200, cron) +} + +// PatchCron updates the cron job in the database. +func PatchCron(c *gin.Context) { + repo := session.Repo(c) + user := session.User(c) + store := store.FromContext(c) + remote := server.Config.Services.Remote + + id, err := strconv.ParseInt(c.Param("cron"), 10, 64) + if err != nil { + c.String(400, "Error parsing cron id. %s", err) + return + } + + in := new(model.Cron) + err = c.Bind(in) + if err != nil { + c.String(http.StatusBadRequest, "Error parsing request. %s", err) + return + } + + cron, err := store.CronFind(repo, id) + if err != nil { + c.String(404, "Error getting cron %d. %s", id, err) + return + } + if in.Branch != "" { + // check if branch exists on remote + _, err := remote.BranchHead(c, user, repo, in.Branch) + if err != nil { + c.String(400, "Error inserting cron. branch not resolved: %s", err) + return + } + cron.Branch = in.Branch + } + if in.Schedule != "" { + cron.Schedule = in.Schedule + nextExec, err := cronScheduler.CalcNewNext(in.Schedule, time.Now()) + if err != nil { + c.String(400, "Error inserting cron. schedule could not parsed: %s", err) + return + } + cron.NextExec = nextExec.Unix() + } + if in.Name != "" { + cron.Name = in.Name + } + cron.CreatorID = user.ID + + if err := cron.Validate(); err != nil { + c.String(400, "Error inserting cron. validate failed: %s", err) + return + } + if err := store.CronUpdate(repo, cron); err != nil { + c.String(500, "Error updating cron %q. %s", in.Name, err) + return + } + c.JSON(200, cron) +} + +// GetCronList gets the cron job list from the database and writes +// to the response in json format. +func GetCronList(c *gin.Context) { + repo := session.Repo(c) + list, err := store.FromContext(c).CronList(repo) + if err != nil { + c.String(500, "Error getting cron list. %s", err) + return + } + c.JSON(200, list) +} + +// DeleteCron deletes the named cron job from the database. +func DeleteCron(c *gin.Context) { + repo := session.Repo(c) + id, err := strconv.ParseInt(c.Param("cron"), 10, 64) + if err != nil { + c.String(400, "Error parsing cron id. %s", err) + return + } + if err := store.FromContext(c).CronDelete(repo, id); err != nil { + c.String(500, "Error deleting cron %d. %s", id, err) + return + } + c.String(204, "") +} diff --git a/server/cron/cron.go b/server/cron/cron.go new file mode 100644 index 000000000..461d86e13 --- /dev/null +++ b/server/cron/cron.go @@ -0,0 +1,141 @@ +// Copyright 2022 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cron + +import ( + "context" + "fmt" + "time" + + "github.com/robfig/cron" + "github.com/rs/zerolog/log" + + "github.com/woodpecker-ci/woodpecker/server" + "github.com/woodpecker-ci/woodpecker/server/model" + "github.com/woodpecker-ci/woodpecker/server/pipeline" + "github.com/woodpecker-ci/woodpecker/server/store" +) + +const ( + // checkTime specifies the interval woodpecker checks for new crons to exec + checkTime = 10 * time.Second + + // checkItems specifies the batch size of crons to retrieve per check from database + checkItems = 10 +) + +// Start starts the cron scheduler loop +func Start(ctx context.Context, store store.Store) error { + for { + select { + case <-ctx.Done(): + return nil + case <-time.After(checkTime): + go func() { + now := time.Now() + log.Trace().Msg("Cron: fetch next crons") + + crons, err := store.CronListNextExecute(now.Unix(), checkItems) + if err != nil { + log.Error().Err(err).Int64("now", now.Unix()).Msg("obtain cron cron list") + return + } + + for _, cron := range crons { + if err := runCron(cron, store, now); err != nil { + log.Error().Err(err).Int64("cronID", cron.ID).Msg("run cron failed") + } + } + }() + } + } +} + +// CalcNewNext parses a cron string and calculates the next exec time based on it +func CalcNewNext(schedule string, now time.Time) (time.Time, error) { + // remove local timezone + now = now.UTC() + + // TODO: allow the users / the admin to set a specific timezone + + c, err := cron.Parse(schedule) + if err != nil { + return time.Time{}, fmt.Errorf("cron parse schedule: %v", err) + } + return c.Next(now), nil +} + +func runCron(cron *model.Cron, store store.Store, now time.Time) error { + log.Trace().Msgf("Cron: run id[%d]", cron.ID) + ctx := context.Background() + + newNext, err := CalcNewNext(cron.Schedule, now) + if err != nil { + return err + } + + // try to get lock on cron + gotLock, err := store.CronGetLock(cron, newNext.Unix()) + if err != nil { + return err + } + if !gotLock { + // another go routine caught it + return nil + } + + repo, newBuild, err := createBuild(ctx, cron, store) + if err != nil { + return err + } + + _, err = pipeline.Create(ctx, store, repo, newBuild) + return err +} + +func createBuild(ctx context.Context, cron *model.Cron, store store.Store) (*model.Repo, *model.Build, error) { + remote := server.Config.Services.Remote + + repo, err := store.GetRepo(cron.RepoID) + if err != nil { + return nil, nil, err + } + + if cron.Branch == "" { + // fallback to the repos default branch + cron.Branch = repo.Branch + } + + creator, err := store.GetUser(cron.CreatorID) + if err != nil { + return nil, nil, err + } + + commit, err := remote.BranchHead(ctx, creator, repo, cron.Branch) + if err != nil { + return nil, nil, err + } + + return repo, &model.Build{ + Event: model.EventCron, + Commit: commit, + Ref: "refs/heads/" + cron.Branch, + Branch: cron.Branch, + Message: cron.Name, + Timestamp: cron.NextExec, + Sender: cron.Name, + Link: repo.Link, + }, nil +} diff --git a/server/cron/cron_test.go b/server/cron/cron_test.go new file mode 100644 index 000000000..cd78a855e --- /dev/null +++ b/server/cron/cron_test.go @@ -0,0 +1,46 @@ +// Copyright 2022 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cron + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/woodpecker-ci/woodpecker/server" + "github.com/woodpecker-ci/woodpecker/server/remote/mocks" +) + +func TestCreateBuild(t *testing.T) { + rOld := server.Config.Services.Remote + defer func() { + server.Config.Services.Remote = rOld + }() + server.Config.Services.Remote = mocks.NewRemote(t) + + // TODO: mockStore + // createBuild(context.TODO(), &model.Cron{}, mockStore) +} + +func TestCalcNewNext(t *testing.T) { + now := time.Unix(1661962369, 0) + _, err := CalcNewNext("", now) + assert.Error(t, err) + + schedule, err := CalcNewNext("@every 5m", now) + assert.NoError(t, err) + assert.EqualValues(t, 1661962669, schedule.Unix()) +} diff --git a/server/model/build.go b/server/model/build.go index 555350896..cd0ed1372 100644 --- a/server/model/build.go +++ b/server/model/build.go @@ -40,7 +40,7 @@ type Build struct { Title string `json:"title" xorm:"build_title"` Message string `json:"message" xorm:"build_message"` Timestamp int64 `json:"timestamp" xorm:"build_timestamp"` - Sender string `json:"sender" xorm:"build_sender"` + Sender string `json:"sender" xorm:"build_sender"` // uses reported user for webhooks and name of cron for cron pipelines Avatar string `json:"author_avatar" xorm:"build_avatar"` Email string `json:"author_email" xorm:"build_email"` Link string `json:"link_url" xorm:"build_link"` diff --git a/server/model/const.go b/server/model/const.go index 6430c0d11..c248bd1f6 100644 --- a/server/model/const.go +++ b/server/model/const.go @@ -21,11 +21,12 @@ const ( EventPull WebhookEvent = "pull_request" EventTag WebhookEvent = "tag" EventDeploy WebhookEvent = "deployment" + EventCron WebhookEvent = "cron" ) func ValidateWebhookEvent(s WebhookEvent) bool { switch s { - case EventPush, EventPull, EventTag, EventDeploy: + case EventPush, EventPull, EventTag, EventDeploy, EventCron: return true default: return false diff --git a/server/model/cron.go b/server/model/cron.go new file mode 100644 index 000000000..1b4c5343c --- /dev/null +++ b/server/model/cron.go @@ -0,0 +1,56 @@ +// Copyright 2022 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package model + +import ( + "fmt" + + "github.com/robfig/cron" +) + +// swagger:model cron +type Cron struct { + ID int64 `json:"id" xorm:"pk autoincr"` + Name string `json:"name" xorm:"UNIQUE(s) INDEX"` + RepoID int64 `json:"repo_id" xorm:"repo_id UNIQUE(s) INDEX"` + CreatorID int64 `json:"creator_id" xorm:"creator_id INDEX"` + NextExec int64 `json:"next_exec"` + Schedule string `json:"schedule" xorm:"NOT NULL"` // @weekly, 3min, ... + Created int64 `json:"created_at" xorm:"created NOT NULL DEFAULT 0"` + Branch string `json:"branch"` +} + +// TableName returns the database table name for xorm +func (Cron) TableName() string { + return "crons" +} + +// Validate a cron +func (c *Cron) Validate() error { + if c.Name == "" { + return fmt.Errorf("name is required") + } + + if c.Schedule == "" { + return fmt.Errorf("schedule is required") + } + + _, err := cron.Parse(c.Schedule) + if err != nil { + return fmt.Errorf("can't parse schedule: %v", err) + } + + return nil +} diff --git a/server/remote/bitbucket/bitbucket.go b/server/remote/bitbucket/bitbucket.go index f17dc227b..e69cd5e2f 100644 --- a/server/remote/bitbucket/bitbucket.go +++ b/server/remote/bitbucket/bitbucket.go @@ -295,6 +295,12 @@ func (c *config) Branches(ctx context.Context, u *model.User, r *model.Repo) ([] return branches, nil } +// BranchHead returns the sha of the head (lastest commit) of the specified branch +func (c *config) BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) { + // TODO(1138): missing implementation + return "", fmt.Errorf("missing implementation") +} + // Hook parses the incoming Bitbucket hook and returns the Repository and // Build details. If the hook is unsupported nil values are returned. func (c *config) Hook(ctx context.Context, req *http.Request) (*model.Repo, *model.Build, error) { diff --git a/server/remote/bitbucketserver/bitbucketserver.go b/server/remote/bitbucketserver/bitbucketserver.go index d807bf60f..8a5d04617 100644 --- a/server/remote/bitbucketserver/bitbucketserver.go +++ b/server/remote/bitbucketserver/bitbucketserver.go @@ -236,6 +236,12 @@ func (c *Config) Branches(ctx context.Context, u *model.User, r *model.Repo) ([] return branches, nil } +// BranchHead returns the sha of the head (lastest commit) of the specified branch +func (c *Config) BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) { + // TODO(1138): missing implementation + return "", fmt.Errorf("missing implementation") +} + func (c *Config) Deactivate(ctx context.Context, u *model.User, r *model.Repo, link string) error { client := internal.NewClientWithToken(ctx, c.URL, c.Consumer, u.Token) return client.DeleteHook(r.Owner, r.Name, link) diff --git a/server/remote/coding/coding.go b/server/remote/coding/coding.go index 194d64010..70ab1403a 100644 --- a/server/remote/coding/coding.go +++ b/server/remote/coding/coding.go @@ -291,6 +291,12 @@ func (c *Coding) Branches(ctx context.Context, u *model.User, r *model.Repo) ([] return []string{r.Branch}, nil } +// BranchHead returns the sha of the head (lastest commit) of the specified branch +func (c *Coding) BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) { + // TODO(1138): missing implementation + return "", fmt.Errorf("missing implementation") +} + // Hook parses the post-commit hook from the Request body and returns the // required data in a standard format. func (c *Coding) Hook(ctx context.Context, r *http.Request) (*model.Repo, *model.Build, error) { diff --git a/server/remote/gitea/gitea.go b/server/remote/gitea/gitea.go index 36d725ae8..e61ade722 100644 --- a/server/remote/gitea/gitea.go +++ b/server/remote/gitea/gitea.go @@ -451,6 +451,25 @@ func (c *Gitea) Branches(ctx context.Context, u *model.User, r *model.Repo) ([]s return branches, nil } +// BranchHead returns the sha of the head (lastest commit) of the specified branch +func (c *Gitea) BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) { + token := "" + if u != nil { + token = u.Token + } + + client, err := c.newClientToken(ctx, token) + if err != nil { + return "", err + } + + b, _, err := client.GetRepoBranch(r.Owner, r.Name, branch) + if err != nil { + return "", err + } + return b.Commit.ID, nil +} + // Hook parses the incoming Gitea hook and returns the Repository and Build // details. If the hook is unsupported nil values are returned. func (c *Gitea) Hook(ctx context.Context, r *http.Request) (*model.Repo, *model.Build, error) { diff --git a/server/remote/github/github.go b/server/remote/github/github.go index 0b90aaa80..122db8fd2 100644 --- a/server/remote/github/github.go +++ b/server/remote/github/github.go @@ -493,6 +493,19 @@ func (c *client) Branches(ctx context.Context, u *model.User, r *model.Repo) ([] return branches, nil } +// BranchHead returns the sha of the head (lastest commit) of the specified branch +func (c *client) BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) { + token := "" + if u != nil { + token = u.Token + } + b, _, err := c.newClientToken(ctx, token).Repositories.GetBranch(ctx, r.Owner, r.Name, branch, true) + if err != nil { + return "", err + } + return b.GetCommit().GetSHA(), nil +} + // Hook parses the post-commit hook from the Request body // and returns the required data in a standard format. func (c *client) Hook(ctx context.Context, r *http.Request) (*model.Repo, *model.Build, error) { diff --git a/server/remote/gitlab/gitlab.go b/server/remote/gitlab/gitlab.go index 2b14f65cb..aa8810a68 100644 --- a/server/remote/gitlab/gitlab.go +++ b/server/remote/gitlab/gitlab.go @@ -545,6 +545,30 @@ func (g *Gitlab) Branches(ctx context.Context, user *model.User, repo *model.Rep return branches, nil } +// BranchHead returns the sha of the head (lastest commit) of the specified branch +func (g *Gitlab) BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) { + token := "" + if u != nil { + token = u.Token + } + client, err := newClient(g.URL, token, g.SkipVerify) + if err != nil { + return "", err + } + + _repo, err := g.getProject(ctx, client, r.Owner, r.Name) + if err != nil { + return "", err + } + + b, _, err := client.Branches.GetBranch(_repo.ID, branch, gitlab.WithContext(ctx)) + if err != nil { + return "", err + } + + return b.Commit.ID, nil +} + // Hook parses the post-commit hook from the Request body // and returns the required data in a standard format. func (g *Gitlab) Hook(ctx context.Context, req *http.Request) (*model.Repo, *model.Build, error) { diff --git a/server/remote/gogs/gogs.go b/server/remote/gogs/gogs.go index 41d6341bd..4a69a0ec6 100644 --- a/server/remote/gogs/gogs.go +++ b/server/remote/gogs/gogs.go @@ -284,6 +284,19 @@ func (c *client) Branches(ctx context.Context, u *model.User, r *model.Repo) ([] return branches, nil } +// BranchHead returns sha of commit on top of the specified branch +func (c *client) BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) { + token := "" + if u != nil { + token = u.Token + } + b, err := c.newClientToken(token).GetRepoBranch(r.Owner, r.Name, branch) + if err != nil { + return "", err + } + return b.Commit.ID, nil +} + // Hook parses the incoming Gogs hook and returns the Repository and Build // details. If the hook is unsupported nil values are returned. func (c *client) Hook(ctx context.Context, r *http.Request) (*model.Repo, *model.Build, error) { diff --git a/server/remote/mocks/remote.go b/server/remote/mocks/remote.go index a3fb7f472..3b2629f80 100644 --- a/server/remote/mocks/remote.go +++ b/server/remote/mocks/remote.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.13.1. DO NOT EDIT. +// Code generated by mockery v2.14.0. DO NOT EDIT. package mocks @@ -53,6 +53,27 @@ func (_m *Remote) Auth(ctx context.Context, token string, secret string) (string return r0, r1 } +// BranchHead provides a mock function with given fields: ctx, u, r, branch +func (_m *Remote) BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) { + ret := _m.Called(ctx, u, r, branch) + + var r0 string + if rf, ok := ret.Get(0).(func(context.Context, *model.User, *model.Repo, string) string); ok { + r0 = rf(ctx, u, r, branch) + } else { + r0 = ret.Get(0).(string) + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *model.User, *model.Repo, string) error); ok { + r1 = rf(ctx, u, r, branch) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // Branches provides a mock function with given fields: ctx, u, r func (_m *Remote) Branches(ctx context.Context, u *model.User, r *model.Repo) ([]string, error) { ret := _m.Called(ctx, u, r) diff --git a/server/remote/remote.go b/server/remote/remote.go index e54cd3bdf..7599c59ed 100644 --- a/server/remote/remote.go +++ b/server/remote/remote.go @@ -77,6 +77,9 @@ type Remote interface { // Branches returns the names of all branches for the named repository. Branches(ctx context.Context, u *model.User, r *model.Repo) ([]string, error) + // BranchHead returns the sha of the head (lastest commit) of the specified branch + BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) + // Hook parses the post-commit hook from the Request body and returns the // required data in a standard format. Hook(ctx context.Context, r *http.Request) (*model.Repo, *model.Build, error) diff --git a/server/router/api.go b/server/router/api.go index 6dddc4ac3..83fdcc603 100644 --- a/server/router/api.go +++ b/server/router/api.go @@ -108,6 +108,13 @@ func apiRoutes(e *gin.Engine) { repo.PATCH("/registry/:registry", session.MustPush, api.PatchRegistry) repo.DELETE("/registry/:registry", session.MustPush, api.DeleteRegistry) + // requires push permissions + repo.GET("/cron", session.MustPush, api.GetCronList) + repo.POST("/cron", session.MustPush, api.PostCron) + repo.GET("/cron/:cron", session.MustPush, api.GetCron) + repo.PATCH("/cron/:cron", session.MustPush, api.PatchCron) + repo.DELETE("/cron/:cron", session.MustPush, api.DeleteCron) + // requires admin permissions repo.PATCH("", session.MustRepoAdmin(), api.PatchRepo) repo.DELETE("", session.MustRepoAdmin(), api.DeleteRepo) diff --git a/server/shared/procBuilder.go b/server/shared/procBuilder.go index 922b9e674..f021b625c 100644 --- a/server/shared/procBuilder.go +++ b/server/shared/procBuilder.go @@ -338,6 +338,11 @@ func metadataFromStruct(repo *model.Repo, build, last *model.Build, proc *model. } func metadataBuildFromModelBuild(build *model.Build, includeParent bool) frontend.Build { + cron := "" + if build.Event == model.EventCron { + cron = build.Sender + } + parent := int64(0) if includeParent { parent = build.Parent @@ -366,6 +371,7 @@ func metadataBuildFromModelBuild(build *model.Build, includeParent bool) fronten }, ChangedFiles: build.ChangedFiles, }, + Cron: cron, } } diff --git a/server/store/datastore/cron.go b/server/store/datastore/cron.go new file mode 100644 index 000000000..247b2b3a0 --- /dev/null +++ b/server/store/datastore/cron.go @@ -0,0 +1,71 @@ +// Copyright 2022 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datastore + +import ( + "github.com/woodpecker-ci/woodpecker/server/model" + + "xorm.io/builder" +) + +func (s storage) CronCreate(cron *model.Cron) error { + if err := cron.Validate(); err != nil { + return err + } + _, err := s.engine.Insert(cron) + return err +} + +func (s storage) CronFind(repo *model.Repo, id int64) (*model.Cron, error) { + cron := &model.Cron{ + RepoID: repo.ID, + ID: id, + } + return cron, wrapGet(s.engine.Get(cron)) +} + +func (s storage) CronList(repo *model.Repo) ([]*model.Cron, error) { + crons := make([]*model.Cron, 0, perPage) + return crons, s.engine.Where("repo_id = ?", repo.ID).Find(&crons) +} + +func (s storage) CronUpdate(repo *model.Repo, cron *model.Cron) error { + _, err := s.engine.ID(cron.ID).AllCols().Update(cron) + return err +} + +func (s storage) CronDelete(repo *model.Repo, id int64) error { + _, err := s.engine.ID(id).Where("repo_id = ?", repo.ID).Delete(new(model.Cron)) + return err +} + +// CronListNextExecute returns limited number of jobs with NextExec being less or equal to the provided unix timestamp +func (s storage) CronListNextExecute(nextExec, limit int64) ([]*model.Cron, error) { + crons := make([]*model.Cron, 0, limit) + return crons, s.engine.Where(builder.Lte{"next_exec": nextExec}).Limit(int(limit)).Find(&crons) +} + +// CronGetLock try to get a lock by updating NextExec +func (s storage) CronGetLock(cron *model.Cron, newNextExec int64) (bool, error) { + cols, err := s.engine.ID(cron.ID).Where(builder.Eq{"next_exec": cron.NextExec}). + Cols("next_exec").Update(&model.Cron{NextExec: newNextExec}) + gotLock := cols != 0 + + if err == nil && gotLock { + cron.NextExec = newNextExec + } + + return gotLock, err +} diff --git a/server/store/datastore/cron_test.go b/server/store/datastore/cron_test.go new file mode 100644 index 000000000..d99cdbad8 --- /dev/null +++ b/server/store/datastore/cron_test.go @@ -0,0 +1,92 @@ +// Copyright 2022 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datastore + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/woodpecker-ci/woodpecker/server/model" +) + +func TestCronCreate(t *testing.T) { + store, closer := newTestStore(t, new(model.Cron)) + defer closer() + + repo := &model.Repo{ID: 1, Name: "repo"} + cron1 := &model.Cron{RepoID: repo.ID, CreatorID: 1, Name: "sync", NextExec: 10000, Schedule: "@every 1h"} + assert.NoError(t, store.CronCreate(cron1)) + assert.NotEqualValues(t, 0, cron1.ID) + + // can not insert cron job with same repoID and title + assert.Error(t, store.CronCreate(cron1)) + + oldID := cron1.ID + assert.NoError(t, store.CronDelete(repo, oldID)) + cron1.ID = 0 + assert.NoError(t, store.CronCreate(cron1)) + assert.NotEqual(t, oldID, cron1.ID) +} + +func TestCronListNextExecute(t *testing.T) { + store, closer := newTestStore(t, new(model.Cron)) + defer closer() + + jobs, err := store.CronListNextExecute(0, 10) + assert.NoError(t, err) + assert.Len(t, jobs, 0) + + now := time.Now().Unix() + + assert.NoError(t, store.CronCreate(&model.Cron{Schedule: "@every 1h", Name: "some", RepoID: 1, NextExec: now})) + assert.NoError(t, store.CronCreate(&model.Cron{Schedule: "@every 1h", Name: "aaaa", RepoID: 1, NextExec: now})) + assert.NoError(t, store.CronCreate(&model.Cron{Schedule: "@every 1h", Name: "bbbb", RepoID: 1, NextExec: now})) + assert.NoError(t, store.CronCreate(&model.Cron{Schedule: "@every 1h", Name: "none", RepoID: 1, NextExec: now + 1000})) + assert.NoError(t, store.CronCreate(&model.Cron{Schedule: "@every 1h", Name: "test", RepoID: 1, NextExec: now + 2000})) + + jobs, err = store.CronListNextExecute(now, 10) + assert.NoError(t, err) + assert.Len(t, jobs, 3) + + jobs, err = store.CronListNextExecute(now+1500, 10) + assert.NoError(t, err) + assert.Len(t, jobs, 4) +} + +func TestCronGetLock(t *testing.T) { + store, closer := newTestStore(t, new(model.Cron)) + defer closer() + + nonExistingJob := &model.Cron{ID: 1000, Name: "locales", NextExec: 10000} + gotLock, err := store.CronGetLock(nonExistingJob, time.Now().Unix()+100) + assert.NoError(t, err) + assert.False(t, gotLock) + + cron1 := &model.Cron{RepoID: 1, Name: "some-title", NextExec: 10000, Schedule: "@every 1h"} + assert.NoError(t, store.CronCreate(cron1)) + + oldJob := *cron1 + gotLock, err = store.CronGetLock(cron1, cron1.NextExec+1000) + assert.NoError(t, err) + assert.True(t, gotLock) + assert.NotEqualValues(t, oldJob.NextExec, cron1.NextExec) + + gotLock, err = store.CronGetLock(&oldJob, oldJob.NextExec+1000) + assert.NoError(t, err) + assert.False(t, gotLock) + assert.EqualValues(t, oldJob.NextExec, oldJob.NextExec) +} diff --git a/server/store/datastore/migration/migration.go b/server/store/datastore/migration/migration.go index a9f13085a..c5f10a050 100644 --- a/server/store/datastore/migration/migration.go +++ b/server/store/datastore/migration/migration.go @@ -52,6 +52,7 @@ var allBeans = []interface{}{ new(model.Task), new(model.User), new(model.ServerConfig), + new(model.Cron), } type migrations struct { diff --git a/server/store/store.go b/server/store/store.go index 5cd32b14e..c27be443b 100644 --- a/server/store/store.go +++ b/server/store/store.go @@ -153,6 +153,15 @@ type Store interface { ServerConfigGet(string) (string, error) ServerConfigSet(string, string) error + // Cron + CronCreate(*model.Cron) error + CronFind(*model.Repo, int64) (*model.Cron, error) + CronList(*model.Repo) ([]*model.Cron, error) + CronUpdate(*model.Repo, *model.Cron) error + CronDelete(*model.Repo, int64) error + CronListNextExecute(int64, int64) ([]*model.Cron, error) + CronGetLock(*model.Cron, int64) (bool, error) + // Store operations Ping() error Close() error diff --git a/web/components.d.ts b/web/components.d.ts index 83f367083..3ade0da58 100644 --- a/web/components.d.ts +++ b/web/components.d.ts @@ -9,6 +9,7 @@ declare module '@vue/runtime-core' { export interface GlobalComponents { ActionsTab: typeof import('./src/components/repo/settings/ActionsTab.vue')['default'] ActiveBuilds: typeof import('./src/components/layout/header/ActiveBuilds.vue')['default'] + AdminSecretsTab: typeof import('./src/components/admin/settings/AdminSecretsTab.vue')['default'] BadgeTab: typeof import('./src/components/repo/settings/BadgeTab.vue')['default'] BuildFeedItem: typeof import('./src/components/build-feed/BuildFeedItem.vue')['default'] BuildFeedSidebar: typeof import('./src/components/build-feed/BuildFeedSidebar.vue')['default'] @@ -22,24 +23,66 @@ declare module '@vue/runtime-core' { Button: typeof import('./src/components/atomic/Button.vue')['default'] Checkbox: typeof import('./src/components/form/Checkbox.vue')['default'] CheckboxesField: typeof import('./src/components/form/CheckboxesField.vue')['default'] + CronTab: typeof import('./src/components/repo/settings/CronTab.vue')['default'] DocsLink: typeof import('./src/components/atomic/DocsLink.vue')['default'] FluidContainer: typeof import('./src/components/layout/FluidContainer.vue')['default'] GeneralTab: typeof import('./src/components/repo/settings/GeneralTab.vue')['default'] + IBxBxPowerOff: typeof import('~icons/bx/bx-power-off')['default'] + ICarbonCloseOutline: typeof import('~icons/carbon/close-outline')['default'] + IClarityDeployLine: typeof import('~icons/clarity/deploy-line')['default'] + IClaritySettingsSolid: typeof import('~icons/clarity/settings-solid')['default'] Icon: typeof import('./src/components/atomic/Icon.vue')['default'] IconButton: typeof import('./src/components/atomic/IconButton.vue')['default'] + IEntypoDotsTwoVertical: typeof import('~icons/entypo/dots-two-vertical')['default'] + IGgTrash: typeof import('~icons/gg/trash')['default'] + IIcBaselineDarkMode: typeof import('~icons/ic/baseline-dark-mode')['default'] + IIcBaselineDownload: typeof import('~icons/ic/baseline-download')['default'] + IIcBaselineEdit: typeof import('~icons/ic/baseline-edit')['default'] + IIcBaselineHealing: typeof import('~icons/ic/baseline-healing')['default'] + IIconoirArrowLeft: typeof import('~icons/iconoir/arrow-left')['default'] + IIconParkOutlineAlarmClock: typeof import('~icons/icon-park-outline/alarm-clock')['default'] + IIcRoundLightMode: typeof import('~icons/ic/round-light-mode')['default'] + IIcSharpTimelapse: typeof import('~icons/ic/sharp-timelapse')['default'] + IIcTwotoneAdd: typeof import('~icons/ic/twotone-add')['default'] + IMdiBitbucket: typeof import('~icons/mdi/bitbucket')['default'] + IMdiChevronRight: typeof import('~icons/mdi/chevron-right')['default'] + IMdiClockTimeEightOutline: typeof import('~icons/mdi/clock-time-eight-outline')['default'] + IMdiFormatListBulleted: typeof import('~icons/mdi/format-list-bulleted')['default'] + IMdiGithub: typeof import('~icons/mdi/github')['default'] + IMdiLoading: typeof import('~icons/mdi/loading')['default'] + IMdiSourceBranch: typeof import('~icons/mdi/source-branch')['default'] + IMdisourceCommit: typeof import('~icons/mdi/source-commit')['default'] + IMdiSourcePull: typeof import('~icons/mdi/source-pull')['default'] + IMdiSync: typeof import('~icons/mdi/sync')['default'] + IMdiTagOutline: typeof import('~icons/mdi/tag-outline')['default'] InputField: typeof import('./src/components/form/InputField.vue')['default'] + IOcticonSkip24: typeof import('~icons/octicon/skip24')['default'] + IPhCheckCircle: typeof import('~icons/ph/check-circle')['default'] + IPhGitlabLogoSimpleFill: typeof import('~icons/ph/gitlab-logo-simple-fill')['default'] + IPhHand: typeof import('~icons/ph/hand')['default'] + IPhHourglass: typeof import('~icons/ph/hourglass')['default'] + IPhProhibit: typeof import('~icons/ph/prohibit')['default'] + IPhWarning: typeof import('~icons/ph/warning')['default'] + IPhXCircle: typeof import('~icons/ph/x-circle')['default'] + ISimpleIconsGitea: typeof import('~icons/simple-icons/gitea')['default'] + ITeenyiconsGitSolid: typeof import('~icons/teenyicons/git-solid')['default'] + IVaadinQuestionCircleO: typeof import('~icons/vaadin/question-circle-o')['default'] ListItem: typeof import('./src/components/atomic/ListItem.vue')['default'] Navbar: typeof import('./src/components/layout/header/Navbar.vue')['default'] NumberField: typeof import('./src/components/form/NumberField.vue')['default'] + OrgSecretsTab: typeof import('./src/components/org/settings/OrgSecretsTab.vue')['default'] Panel: typeof import('./src/components/layout/Panel.vue')['default'] RadioField: typeof import('./src/components/form/RadioField.vue')['default'] RegistriesTab: typeof import('./src/components/repo/settings/RegistriesTab.vue')['default'] RouterLink: typeof import('vue-router')['RouterLink'] RouterView: typeof import('vue-router')['RouterView'] + SecretEdit: typeof import('./src/components/secrets/SecretEdit.vue')['default'] + SecretList: typeof import('./src/components/secrets/SecretList.vue')['default'] SecretsTab: typeof import('./src/components/repo/settings/SecretsTab.vue')['default'] SelectField: typeof import('./src/components/form/SelectField.vue')['default'] Tab: typeof import('./src/components/tabs/Tab.vue')['default'] Tabs: typeof import('./src/components/tabs/Tabs.vue')['default'] TextField: typeof import('./src/components/form/TextField.vue')['default'] + Warning: typeof import('./src/components/atomic/Warning.vue')['default'] } } diff --git a/web/src/assets/locales/en.json b/web/src/assets/locales/en.json index 77cdcc4be..e76b58d4f 100644 --- a/web/src/assets/locales/en.json +++ b/web/src/assets/locales/en.json @@ -122,6 +122,31 @@ "placeholder": "Registry Address (e.g. docker.io)" } }, + "crons": { + "crons": "Crons", + "desc": "Cron jobs can be used to trigger pipelines on a regular basis.", + "show": "Show crons", + "add": "Add cron", + "none": "There are no crons yet.", + "save": "Save cron", + "created": "Cron created", + "saved": "Cron saved", + "deleted": "Cron deleted", + "next_exec": "Next execution", + "not_executed_yet": "Not executed yet", + "branch": { + "title": "Branch", + "placeholder": "Branch (uses default branch if empty)" + }, + "name": { + "name": "Name", + "placeholder": "Name of the cron job" + }, + "schedule": { + "title": "Schedule (based on UTC)", + "placeholder": "Schedule" + } + }, "badge": { "badge": "Badge", "url_branch": "URL for specific branch", @@ -179,7 +204,8 @@ "push": "Push", "tag": "Tag", "pr": "Pull Request", - "deploy": "Deploy" + "deploy": "Deploy", + "cron": "Cron" } } }, diff --git a/web/src/components/atomic/DocsLink.vue b/web/src/components/atomic/DocsLink.vue index f0b42394c..5d055f343 100644 --- a/web/src/components/atomic/DocsLink.vue +++ b/web/src/components/atomic/DocsLink.vue @@ -1,32 +1,22 @@ - diff --git a/web/src/components/atomic/Icon.vue b/web/src/components/atomic/Icon.vue index 6d05b830f..68ab56659 100644 --- a/web/src/components/atomic/Icon.vue +++ b/web/src/components/atomic/Icon.vue @@ -37,6 +37,7 @@ +
@@ -82,6 +83,7 @@ export type IconNames = | 'turn-off' | 'close' | 'edit' + | 'stopwatch' | 'download'; export default defineComponent({ diff --git a/web/src/components/repo/build/BuildItem.vue b/web/src/components/repo/build/BuildItem.vue index bb9bb68ff..33aeedf43 100644 --- a/web/src/components/repo/build/BuildItem.vue +++ b/web/src/components/repo/build/BuildItem.vue @@ -19,7 +19,8 @@
- + +
@@ -33,6 +34,7 @@ + {{ prettyRef }}
diff --git a/web/src/components/repo/build/BuildProcList.vue b/web/src/components/repo/build/BuildProcList.vue index cf4d9389f..518054636 100644 --- a/web/src/components/repo/build/BuildProcList.vue +++ b/web/src/components/repo/build/BuildProcList.vue @@ -4,7 +4,10 @@ class="flex md:ml-2 p-4 space-x-1 justify-between flex-shrink-0 border-b-1 md:rounded-md bg-gray-300 dark:border-b-dark-gray-600 dark:bg-dark-gray-700" >
-
+
+ + +
{{ build.author }}
diff --git a/web/src/components/repo/settings/CronTab.vue b/web/src/components/repo/settings/CronTab.vue new file mode 100644 index 000000000..5e4bceb82 --- /dev/null +++ b/web/src/components/repo/settings/CronTab.vue @@ -0,0 +1,155 @@ + + + diff --git a/web/src/components/secrets/SecretEdit.vue b/web/src/components/secrets/SecretEdit.vue index 99c594b39..678165e0c 100644 --- a/web/src/components/secrets/SecretEdit.vue +++ b/web/src/components/secrets/SecretEdit.vue @@ -111,6 +111,7 @@ export default defineComponent({ description: i18n.t('repo.settings.secrets.events.pr_warning'), }, { value: WebhookEvents.Deploy, text: i18n.t('repo.build.event.deploy') }, + { value: WebhookEvents.Cron, text: i18n.t('repo.build.event.cron') }, ]; function save() { diff --git a/web/src/compositions/useBuild.ts b/web/src/compositions/useBuild.ts index eb98d2b1e..1d5d03302 100644 --- a/web/src/compositions/useBuild.ts +++ b/web/src/compositions/useBuild.ts @@ -87,6 +87,10 @@ export default (build: Ref) => { return build.value.branch; } + if (build.value?.event === 'cron') { + return build.value.ref.replaceAll('refs/heads/', ''); + } + if (build.value?.event === 'tag') { return build.value.ref.replaceAll('refs/tags/', ''); } diff --git a/web/src/lib/api/index.ts b/web/src/lib/api/index.ts index 77d08676b..dc4e17ef9 100644 --- a/web/src/lib/api/index.ts +++ b/web/src/lib/api/index.ts @@ -12,6 +12,7 @@ import { RepoSettings, Secret, } from './types'; +import { Cron } from './types/cron'; type RepoListOptions = { all?: boolean; @@ -136,6 +137,22 @@ export default class WoodpeckerClient extends ApiClient { return this._delete(`/api/repos/${owner}/${repo}/registry/${registryAddress}`); } + getCronList(owner: string, repo: string): Promise { + return this._get(`/api/repos/${owner}/${repo}/cron`) as Promise; + } + + createCron(owner: string, repo: string, cron: Partial): Promise { + return this._post(`/api/repos/${owner}/${repo}/cron`, cron); + } + + updateCron(owner: string, repo: string, cron: Partial): Promise { + return this._patch(`/api/repos/${owner}/${repo}/cron/${cron.id}`, cron); + } + + deleteCron(owner: string, repo: string, cronId: number): Promise { + return this._delete(`/api/repos/${owner}/${repo}/cron/${cronId}`); + } + getOrgPermissions(owner: string): Promise { return this._get(`/api/orgs/${owner}/permissions`) as Promise; } diff --git a/web/src/lib/api/types/build.ts b/web/src/lib/api/types/build.ts index e5f931d38..12c73de12 100644 --- a/web/src/lib/api/types/build.ts +++ b/web/src/lib/api/types/build.ts @@ -8,7 +8,7 @@ export type Build = { parent: number; - event: 'push' | 'tag' | 'pull_request' | 'deployment'; + event: 'push' | 'tag' | 'pull_request' | 'deployment' | 'cron'; // The current status of the build. status: BuildStatus; diff --git a/web/src/lib/api/types/cron.ts b/web/src/lib/api/types/cron.ts new file mode 100644 index 000000000..64d35c3da --- /dev/null +++ b/web/src/lib/api/types/cron.ts @@ -0,0 +1,7 @@ +export type Cron = { + id: number; + name: string; + branch: string; + schedule: string; + next_exec: number; +}; diff --git a/web/src/lib/api/types/index.ts b/web/src/lib/api/types/index.ts index d68a8ee19..a63f1e69d 100644 --- a/web/src/lib/api/types/index.ts +++ b/web/src/lib/api/types/index.ts @@ -1,5 +1,6 @@ export * from './build'; export * from './buildConfig'; +export * from './cron'; export * from './org'; export * from './registry'; export * from './repo'; diff --git a/web/src/lib/api/types/webhook.ts b/web/src/lib/api/types/webhook.ts index 9b121f657..b318357ef 100644 --- a/web/src/lib/api/types/webhook.ts +++ b/web/src/lib/api/types/webhook.ts @@ -3,4 +3,5 @@ export enum WebhookEvents { Tag = 'tag', PullRequest = 'pull_request', Deploy = 'deployment', + Cron = 'cron', } diff --git a/web/src/views/repo/RepoSettings.vue b/web/src/views/repo/RepoSettings.vue index 9625c7c99..f1dbc221a 100644 --- a/web/src/views/repo/RepoSettings.vue +++ b/web/src/views/repo/RepoSettings.vue @@ -15,6 +15,9 @@ + + + @@ -25,8 +28,8 @@ - diff --git a/woodpecker-go/woodpecker/client.go b/woodpecker-go/woodpecker/client.go index 19ea17882..3deb592be 100644 --- a/woodpecker-go/woodpecker/client.go +++ b/woodpecker-go/woodpecker/client.go @@ -29,6 +29,8 @@ const ( pathRepoSecret = "%s/api/repos/%s/%s/secrets/%s" pathRepoRegistries = "%s/api/repos/%s/%s/registry" pathRepoRegistry = "%s/api/repos/%s/%s/registry/%s" + pathRepoCrons = "%s/api/repos/%s/%s/cron" + pathRepoCron = "%s/api/repos/%s/%s/cron/%d" pathOrgSecrets = "%s/api/orgs/%s/secrets" pathOrgSecret = "%s/api/orgs/%s/secrets/%s" pathGlobalSecrets = "%s/api/secrets" @@ -463,6 +465,36 @@ func (c *client) SetLogLevel(in *LogLevel) (*LogLevel, error) { return out, err } +func (c *client) CronList(owner, repo string) ([]*Cron, error) { + out := make([]*Cron, 0, 5) + uri := fmt.Sprintf(pathRepoCrons, c.addr, owner, repo) + return out, c.get(uri, &out) +} + +func (c *client) CronCreate(owner, repo string, in *Cron) (*Cron, error) { + out := new(Cron) + uri := fmt.Sprintf(pathRepoCrons, c.addr, owner, repo) + return out, c.post(uri, in, out) +} + +func (c *client) CronUpdate(owner, repo string, in *Cron) (*Cron, error) { + out := new(Cron) + uri := fmt.Sprintf(pathRepoCron, c.addr, owner, repo, in.ID) + err := c.patch(uri, in, out) + return out, err +} + +func (c *client) CronDelete(owner, repo string, cronID int64) error { + uri := fmt.Sprintf(pathRepoCron, c.addr, owner, repo, cronID) + return c.delete(uri) +} + +func (c *client) CronGet(owner, repo string, cronID int64) (*Cron, error) { + out := new(Cron) + uri := fmt.Sprintf(pathRepoCron, c.addr, owner, repo, cronID) + return out, c.get(uri, out) +} + // // http request helper functions // diff --git a/woodpecker-go/woodpecker/interface.go b/woodpecker-go/woodpecker/interface.go index 102b1b601..43a77e104 100644 --- a/woodpecker-go/woodpecker/interface.go +++ b/woodpecker-go/woodpecker/interface.go @@ -166,4 +166,19 @@ type Client interface { // SetLogLevel sets the server's logging level SetLogLevel(logLevel *LogLevel) (*LogLevel, error) + + // CronList list all cron jobs of a repo + CronList(owner, repo string) ([]*Cron, error) + + // CronGet get a specific cron job of a repo by id + CronGet(owner, repo string, cronID int64) (*Cron, error) + + // CronDelete delete a specific cron job of a repo by id + CronDelete(owner, repo string, cronID int64) error + + // CronCreate create a new cron job in a repo + CronCreate(owner, repo string, cron *Cron) (*Cron, error) + + // CronUpdate update an existing cron job of a repo + CronUpdate(owner, repo string, cron *Cron) (*Cron, error) } diff --git a/woodpecker-go/woodpecker/types.go b/woodpecker-go/woodpecker/types.go index 7a94af963..04b4a850a 100644 --- a/woodpecker-go/woodpecker/types.go +++ b/woodpecker-go/woodpecker/types.go @@ -163,4 +163,16 @@ type ( Proc string `json:"proc"` Output string `json:"out"` } + + // Cron is the JSON data of a cron job + Cron struct { + ID int64 `json:"id"` + Name string `json:"name"` + RepoID int64 `json:"repo_id"` + CreatorID int64 `json:"creator_id"` + NextExec int64 `json:"next_exec"` + Schedule string `json:"schedule"` + Created int64 `json:"created_at"` + Branch string `json:"branch"` + } )