aboutsummaryrefslogtreecommitdiffstats
path: root/models/admin/task.go
blob: c8bc95f98142520d7d8ae0816a3ab91df154597e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright 2019 Gitea. All rights reserved.
// SPDX-License-Identifier: MIT

package admin

import (
	"context"
	"fmt"

	"code.gitea.io/gitea/models/db"
	repo_model "code.gitea.io/gitea/models/repo"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/json"
	"code.gitea.io/gitea/modules/migration"
	"code.gitea.io/gitea/modules/secret"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/structs"
	"code.gitea.io/gitea/modules/timeutil"
	"code.gitea.io/gitea/modules/util"
)

// Task represents a task
type Task struct {
	ID             int64
	DoerID         int64                  `xorm:"index"` // operator
	Doer           *user_model.User       `xorm:"-"`
	OwnerID        int64                  `xorm:"index"` // repo owner id, when creating, the repoID maybe zero
	Owner          *user_model.User       `xorm:"-"`
	RepoID         int64                  `xorm:"index"`
	Repo           *repo_model.Repository `xorm:"-"`
	Type           structs.TaskType
	Status         structs.TaskStatus `xorm:"index"`
	StartTime      timeutil.TimeStamp
	EndTime        timeutil.TimeStamp
	PayloadContent string             `xorm:"TEXT"`
	Message        string             `xorm:"TEXT"` // if task failed, saved the error reason, it could be a JSON string of TranslatableMessage or a plain message
	Created        timeutil.TimeStamp `xorm:"created"`
}

func init() {
	db.RegisterModel(new(Task))
}

// TranslatableMessage represents JSON struct that can be translated with a Locale
type TranslatableMessage struct {
	Format string
	Args   []any `json:"omitempty"`
}

// LoadRepo loads repository of the task
func (task *Task) LoadRepo(ctx context.Context) error {
	if task.Repo != nil {
		return nil
	}
	var repo repo_model.Repository
	has, err := db.GetEngine(ctx).ID(task.RepoID).Get(&repo)
	if err != nil {
		return err
	} else if !has {
		return repo_model.ErrRepoNotExist{
			ID: task.RepoID,
		}
	}
	task.Repo = &repo
	return nil
}

// LoadDoer loads do user
func (task *Task) LoadDoer(ctx context.Context) error {
	if task.Doer != nil {
		return nil
	}

	var doer user_model.User
	has, err := db.GetEngine(ctx).ID(task.DoerID).Get(&doer)
	if err != nil {
		return err
	} else if !has {
		return user_model.ErrUserNotExist{
			UID: task.DoerID,
		}
	}
	task.Doer = &doer

	return nil
}

// LoadOwner loads owner user
func (task *Task) LoadOwner(ctx context.Context) error {
	if task.Owner != nil {
		return nil
	}

	var owner user_model.User
	has, err := db.GetEngine(ctx).ID(task.OwnerID).Get(&owner)
	if err != nil {
		return err
	} else if !has {
		return user_model.ErrUserNotExist{
			UID: task.OwnerID,
		}
	}
	task.Owner = &owner

	return nil
}

// UpdateCols updates some columns
func (task *Task) UpdateCols(ctx context.Context, cols ...string) error {
	_, err := db.GetEngine(ctx).ID(task.ID).Cols(cols...).Update(task)
	return err
}

// MigrateConfig returns task config when migrate repository
func (task *Task) MigrateConfig() (*migration.MigrateOptions, error) {
	if task.Type == structs.TaskTypeMigrateRepo {
		var opts migration.MigrateOptions
		err := json.Unmarshal([]byte(task.PayloadContent), &opts)
		if err != nil {
			return nil, err
		}

		// decrypt credentials
		if opts.CloneAddrEncrypted != "" {
			if opts.CloneAddr, err = secret.DecryptSecret(setting.SecretKey, opts.CloneAddrEncrypted); err != nil {
				return nil, err
			}
		}
		if opts.AuthPasswordEncrypted != "" {
			if opts.AuthPassword, err = secret.DecryptSecret(setting.SecretKey, opts.AuthPasswordEncrypted); err != nil {
				return nil, err
			}
		}
		if opts.AuthTokenEncrypted != "" {
			if opts.AuthToken, err = secret.DecryptSecret(setting.SecretKey, opts.AuthTokenEncrypted); err != nil {
				return nil, err
			}
		}

		return &opts, nil
	}
	return nil, fmt.Errorf("Task type is %s, not Migrate Repo", task.Type.Name())
}

// ErrTaskDoesNotExist represents a "TaskDoesNotExist" kind of error.
type ErrTaskDoesNotExist struct {
	ID     int64
	RepoID int64
	Type   structs.TaskType
}

// IsErrTaskDoesNotExist checks if an error is a ErrTaskDoesNotExist.
func IsErrTaskDoesNotExist(err error) bool {
	_, ok := err.(ErrTaskDoesNotExist)
	return ok
}

func (err ErrTaskDoesNotExist) Error() string {
	return fmt.Sprintf("task does not exist [id: %d, repo_id: %d, type: %d]",
		err.ID, err.RepoID, err.Type)
}

func (err ErrTaskDoesNotExist) Unwrap() error {
	return util.ErrNotExist
}

// GetMigratingTask returns the migrating task by repo's id
func GetMigratingTask(ctx context.Context, repoID int64) (*Task, error) {
	task := Task{
		RepoID: repoID,
		Type:   structs.TaskTypeMigrateRepo,
	}
	has, err := db.GetEngine(ctx).Get(&task)
	if err != nil {
		return nil, err
	} else if !has {
		return nil, ErrTaskDoesNotExist{0, repoID, task.Type}
	}
	return &task, nil
}

// GetMigratingTaskByID returns the migrating task by repo's id
func GetMigratingTaskByID(ctx context.Context, id, doerID int64) (*Task, *migration.MigrateOptions, error) {
	task := Task{
		ID:     id,
		DoerID: doerID,
		Type:   structs.TaskTypeMigrateRepo,
	}
	has, err := db.GetEngine(ctx).Get(&task)
	if err != nil {
		return nil, nil, err
	} else if !has {
		return nil, nil, ErrTaskDoesNotExist{id, 0, task.Type}
	}

	var opts migration.MigrateOptions
	if err := json.Unmarshal([]byte(task.PayloadContent), &opts); err != nil {
		return nil, nil, err
	}
	return &task, &opts, nil
}

// CreateTask creates a task on database
func CreateTask(ctx context.Context, task *Task) error {
	return db.Insert(ctx, task)
}

// FinishMigrateTask updates database when migrate task finished
func FinishMigrateTask(ctx context.Context, task *Task) error {
	task.Status = structs.TaskStatusFinished
	task.EndTime = timeutil.TimeStampNow()

	// delete credentials when we're done, they're a liability.
	conf, err := task.MigrateConfig()
	if err != nil {
		return err
	}
	conf.AuthPassword = ""
	conf.AuthToken = ""
	conf.CloneAddr = util.SanitizeCredentialURLs(conf.CloneAddr)
	conf.AuthPasswordEncrypted = ""
	conf.AuthTokenEncrypted = ""
	conf.CloneAddrEncrypted = ""
	confBytes, err := json.Marshal(conf)
	if err != nil {
		return err
	}
	task.PayloadContent = string(confBytes)

	_, err = db.GetEngine(ctx).ID(task.ID).Cols("status", "end_time", "payload_content").Update(task)
	return err
}