Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support changing labels of Actions runner without re-registration #24806

Merged
merged 27 commits into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module code.gitea.io/gitea
go 1.20

require (
code.gitea.io/actions-proto-go v0.2.1
code.gitea.io/actions-proto-go v0.3.0
code.gitea.io/gitea-vet v0.2.2
code.gitea.io/sdk/gitea v0.15.1
codeberg.org/gusted/mcaptcha v0.0.0-20220723083913-4f3072e1d570
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo=
code.gitea.io/actions-proto-go v0.2.1 h1:ToMN/8thz2q10TuCq8dL2d8mI+/pWpJcHCvG+TELwa0=
code.gitea.io/actions-proto-go v0.2.1/go.mod h1:00ys5QDo1iHN1tHNvvddAcy2W/g+425hQya1cCSvq9A=
code.gitea.io/actions-proto-go v0.3.0 h1:9Tvg8+TaaCXPKi6EnWl9vVgs2VZsj1Cs5afnsHa4AmM=
code.gitea.io/actions-proto-go v0.3.0/go.mod h1:00ys5QDo1iHN1tHNvvddAcy2W/g+425hQya1cCSvq9A=
code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE=
code.gitea.io/gitea-vet v0.2.2 h1:TEOV/Glf38iGmKzKP0EB++Z5OSL4zGg3RrAvlwaMuvk=
code.gitea.io/gitea-vet v0.2.2/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE=
Expand Down
12 changes: 3 additions & 9 deletions models/actions/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,9 @@ type ActionRunner struct {
LastOnline timeutil.TimeStamp `xorm:"index"`
LastActive timeutil.TimeStamp `xorm:"index"`

// Store OS and Artch.
AgentLabels []string
// Store custom labes use defined.
CustomLabels []string
// Store labels defined in state file (default: .runner file) of `act_runner`
// Replace the previous AgentLabels and CustomLabels
Labels []string `xorm:"TEXT"`

Created timeutil.TimeStamp `xorm:"created"`
Updated timeutil.TimeStamp `xorm:"updated"`
Expand Down Expand Up @@ -104,11 +103,6 @@ func (r *ActionRunner) IsOnline() bool {
return false
}

// AllLabels returns agent and custom labels
func (r *ActionRunner) AllLabels() []string {
return append(r.AgentLabels, r.CustomLabels...)
}

// Editable checks if the runner is editable by the user
func (r *ActionRunner) Editable(ownerID, repoID int64) bool {
if ownerID == 0 && repoID == 0 {
Expand Down
3 changes: 1 addition & 2 deletions models/actions/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,7 @@ func CreateTaskForRunner(ctx context.Context, runner *ActionRunner) (*ActionTask

// TODO: a more efficient way to filter labels
var job *ActionRunJob
labels := runner.AgentLabels
labels = append(labels, runner.CustomLabels...)
labels := runner.Labels
log.Trace("runner labels: %v", labels)
for _, v := range jobs {
if isSubset(labels, v.RunsOn) {
Expand Down
6 changes: 6 additions & 0 deletions models/migrations/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"code.gitea.io/gitea/models/migrations/v1_18"
"code.gitea.io/gitea/models/migrations/v1_19"
"code.gitea.io/gitea/models/migrations/v1_20"
"code.gitea.io/gitea/models/migrations/v1_21"
"code.gitea.io/gitea/models/migrations/v1_6"
"code.gitea.io/gitea/models/migrations/v1_7"
"code.gitea.io/gitea/models/migrations/v1_8"
Expand Down Expand Up @@ -497,6 +498,11 @@ var migrations = []Migration{
NewMigration("Add PinOrder Column", v1_20.AddPinOrderToIssue),
// v259 -> 260
NewMigration("Convert scoped access tokens", v1_20.ConvertScopedAccessTokens),

// Gitea 1.20.0 ends at 260

// v260 -> v261
sillyguodong marked this conversation as resolved.
Show resolved Hide resolved
NewMigration("Add label column to action_run table, and combine labels", v1_21.AddLabelsToActRunner),
sillyguodong marked this conversation as resolved.
Show resolved Hide resolved
}

// GetCurrentDBVersion returns the current db version
Expand Down
14 changes: 14 additions & 0 deletions models/migrations/v1_21/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package v1_21 //nolint

import (
"testing"

"code.gitea.io/gitea/models/migrations/base"
)

func TestMain(m *testing.M) {
base.MainTest(m)
}
53 changes: 53 additions & 0 deletions models/migrations/v1_21/v260.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package v1_21 //nolint

import (
"code.gitea.io/gitea/models/migrations/base"

"xorm.io/xorm"
)

func AddLabelsToActRunner(x *xorm.Engine) error {
sillyguodong marked this conversation as resolved.
Show resolved Hide resolved
sess := x.NewSession()
defer sess.Close()

if err := sess.Begin(); err != nil {
return err
}

type ActionRunner struct {
ID int64
AgentLabels []string
CustomLabels []string
Labels []string `xorm:"TEXT"` // new column
}

// add column of `labels` to the `action_runner` table.
if err := sess.Sync(new(ActionRunner)); err != nil {
return err
}

// combine "agent_labels" col and "custom_labels" col to "labels" col.
var runners []*ActionRunner
if err := sess.Table("action_runner").Select("id, agent_labels, custom_labels").Find(&runners); err != nil {
return err
}

for _, r := range runners {
sillyguodong marked this conversation as resolved.
Show resolved Hide resolved
r.Labels = append(r.Labels, r.AgentLabels...)
r.Labels = append(r.Labels, r.CustomLabels...)
sillyguodong marked this conversation as resolved.
Show resolved Hide resolved

if _, err := sess.ID(r.ID).Cols("labels").Update(r); err != nil {
return err
}
}

// drop "agent_labels" and "custom_labels" cols
if err := base.DropTableColumns(sess, "action_runner", "agent_labels", "custom_labels"); err != nil {
return err
}

return sess.Commit()
}
3 changes: 0 additions & 3 deletions options/locale/locale_en-US.ini
Original file line number Diff line number Diff line change
Expand Up @@ -3423,9 +3423,6 @@ runners.owner_type = Type
runners.description = Description
runners.labels = Labels
runners.last_online = Last Online Time
runners.agent_labels = Agent Labels
runners.custom_labels = Custom Labels
runners.custom_labels_helper = Custom labels are labels that are added manually by an administrator. A comma separates labels, whitespace at the start and end of each label is ignored.
runners.runner_title = Runner
runners.task_list = Recent tasks on this runner
runners.task_list.run = Run
Expand Down
19 changes: 10 additions & 9 deletions routers/api/actions/runner/interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,10 @@ import (
)

const (
uuidHeaderKey = "x-runner-uuid"
tokenHeaderKey = "x-runner-token"
uuidHeaderKey = "x-runner-uuid"
tokenHeaderKey = "x-runner-token"
// Deprecated: will be removed after Gitea 1.20 released.
versionHeaderKey = "x-runner-version"

versionUnknown = "Unknown"
)

var withRunner = connect.WithInterceptors(connect.UnaryInterceptorFunc(func(unaryFunc connect.UnaryFunc) connect.UnaryFunc {
Expand All @@ -36,11 +35,9 @@ var withRunner = connect.WithInterceptors(connect.UnaryInterceptorFunc(func(unar
}
uuid := request.Header().Get(uuidHeaderKey)
token := request.Header().Get(tokenHeaderKey)
// TODO: version will be removed from request header after Gitea 1.20 released.
// And Gitea will not try to read version from reuqest header
version := request.Header().Get(versionHeaderKey)
if util.IsEmptyString(version) {
version = versionUnknown
}
version, _ = util.SplitStringAtByteN(version, 64)

runner, err := actions_model.GetRunnerByUUID(ctx, uuid)
if err != nil {
Expand All @@ -54,7 +51,11 @@ var withRunner = connect.WithInterceptors(connect.UnaryInterceptorFunc(func(unar
}

cols := []string{"last_online"}
if runner.Version != version {

// TODO: version will be removed from request header after Gitea 1.20 released.
// And Gitea will not try to read version from reuqest header
version, _ = util.SplitStringAtByteN(version, 64)
if !util.IsEmptyString(version) && runner.Version != version {
runner.Version = version
cols = append(cols, "version")
}
Expand Down
55 changes: 43 additions & 12 deletions routers/api/actions/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,23 @@ func (s *Service) Register(
return nil, errors.New("runner token has already been activated")
}

labels := req.Msg.Labels
// TODO: agent_labels should be removed from pb after Gitea 1.20 released.
// Old version runner's agent_labels slice is not empty and labels slice is empty.
// And due to compatibility with older versions, it is temporarily marked as Deprecated in pb, so use `//nolint` here.
if len(req.Msg.AgentLabels) > 0 && len(req.Msg.Labels) == 0 { //nolint:staticcheck
labels = req.Msg.AgentLabels //nolint:staticcheck
}

// create new runner
name, _ := util.SplitStringAtByteN(req.Msg.Name, 255)
runner := &actions_model.ActionRunner{
UUID: gouuid.New().String(),
Name: name,
OwnerID: runnerToken.OwnerID,
RepoID: runnerToken.RepoID,
AgentLabels: req.Msg.AgentLabels,
CustomLabels: req.Msg.CustomLabels,
UUID: gouuid.New().String(),
Name: name,
OwnerID: runnerToken.OwnerID,
RepoID: runnerToken.RepoID,
Version: req.Msg.Version,
Labels: labels,
}
if err := runner.GenerateToken(); err != nil {
return nil, errors.New("can't generate token")
Expand All @@ -81,18 +89,41 @@ func (s *Service) Register(

res := connect.NewResponse(&runnerv1.RegisterResponse{
Runner: &runnerv1.Runner{
Id: runner.ID,
Uuid: runner.UUID,
Token: runner.Token,
Name: runner.Name,
AgentLabels: runner.AgentLabels,
CustomLabels: runner.CustomLabels,
Id: runner.ID,
Uuid: runner.UUID,
Token: runner.Token,
Name: runner.Name,
Version: runner.Version,
Labels: runner.Labels,
},
})

return res, nil
}

func (s *Service) Declare(
ctx context.Context,
req *connect.Request[runnerv1.DeclareRequest],
) (*connect.Response[runnerv1.DeclareResponse], error) {
runner := GetRunner(ctx)
runner.Labels = req.Msg.Labels
runner.Version = req.Msg.Version
if err := actions_model.UpdateRunner(ctx, runner, "labels", "version"); err != nil {
return nil, status.Errorf(codes.Internal, "update runner: %v", err)
}

return connect.NewResponse(&runnerv1.DeclareResponse{
Runner: &runnerv1.Runner{
Id: runner.ID,
Uuid: runner.UUID,
Token: runner.Token,
Name: runner.Name,
Version: runner.Version,
Labels: runner.Labels,
},
}), nil
}

// FetchTask assigns a task to the runner
func (s *Service) FetchTask(
ctx context.Context,
Expand Down
3 changes: 1 addition & 2 deletions routers/web/repo/actions/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,7 @@ func List(ctx *context.Context) {
}
allRunnerLabels := make(container.Set[string])
for _, r := range runners {
allRunnerLabels.AddMultiple(r.AgentLabels...)
allRunnerLabels.AddMultiple(r.CustomLabels...)
allRunnerLabels.AddMultiple(r.Labels...)
}

workflows = make([]Workflow, 0, len(entries))
Expand Down
12 changes: 1 addition & 11 deletions routers/web/shared/actions/runners.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ package actions
import (
"errors"
"net/http"
"strings"

actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
Expand Down Expand Up @@ -126,9 +125,8 @@ func RunnerDetailsEditPost(ctx *context.Context, runnerID, ownerID, repoID int64

form := web.GetForm(ctx).(*forms.EditRunnerForm)
runner.Description = form.Description
runner.CustomLabels = splitLabels(form.CustomLabels)

err = actions_model.UpdateRunner(ctx, runner, "description", "custom_labels")
err = actions_model.UpdateRunner(ctx, runner, "description")
sillyguodong marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
log.Warn("RunnerDetailsEditPost.UpdateRunner failed: %v, url: %s", err, ctx.Req.URL)
ctx.Flash.Warning(ctx.Tr("actions.runners.update_runner_failed"))
Expand Down Expand Up @@ -176,11 +174,3 @@ func RunnerDeletePost(ctx *context.Context, runnerID int64,
"redirect": successRedirectTo,
})
}

func splitLabels(s string) []string {
labels := strings.Split(s, ",")
for i, v := range labels {
labels[i] = strings.TrimSpace(v)
}
return labels
}
3 changes: 1 addition & 2 deletions services/forms/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ import (

// EditRunnerForm form for admin to create runner
type EditRunnerForm struct {
Description string
CustomLabels string // comma-separated
Description string
}

// Validate validates form fields
Expand Down
9 changes: 2 additions & 7 deletions templates/shared/actions/runner_edit.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
<span>{{if .LastOnline}}{{TimeSinceUnix .LastOnline $.locale}}{{else}}{{$.locale.Tr "never"}}{{end}}</span>
</div>
<div class="field gt-dib gt-mr-4">
<label>{{.locale.Tr "actions.runners.agent_labels"}}</label>
<label>{{.locale.Tr "actions.runners.labels"}}</label>
sillyguodong marked this conversation as resolved.
Show resolved Hide resolved
<span>
{{range .Runner.AgentLabels}}
{{range .Runner.Labels}}
<span>{{.}}</span>
{{end}}
</span>
Expand All @@ -35,11 +35,6 @@
<label for="description">{{.locale.Tr "actions.runners.description"}}</label>
<input id="description" name="description" value="{{.Runner.Description}}">
</div>
<div class="field" data-tooltip-content="Labels are comma-separated. Whitespace at the beginning, end, and around the commas are ignored.">
<label for="custom_labels">{{.locale.Tr "actions.runners.custom_labels"}}</label>
<input id="custom_labels" name="custom_labels" value="{{StringUtils.Join .Runner.CustomLabels `,`}}">
<p class="help">{{.locale.Tr "actions.runners.custom_labels_helper"}}</p>
</div>

<div class="ui divider"></div>

Expand Down
2 changes: 1 addition & 1 deletion templates/shared/actions/runner_list.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
<td>{{if .Version}}{{.Version}}{{else}}{{$.locale.Tr "unknown"}}{{end}}</td>
<td><span data-tooltip-content="{{.BelongsToOwnerName}}">{{.BelongsToOwnerType.LocaleString $.locale}}<span></td>
<td class="runner-tags">
{{range .AllLabels}}<span class="ui label">{{.}}</span>{{end}}
{{range .Labels}}<span class="ui label">{{.}}</span>{{end}}
</td>
<td>{{if .LastOnline}}{{TimeSinceUnix .LastOnline $.locale}}{{else}}{{$.locale.Tr "never"}}{{end}}</td>
<td class="runner-ops">
Expand Down