gitea源码

commit_status.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // Copyright 2017 Gitea. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package git
  4. import (
  5. "context"
  6. "crypto/sha1"
  7. "errors"
  8. "fmt"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "time"
  13. asymkey_model "code.gitea.io/gitea/models/asymkey"
  14. "code.gitea.io/gitea/models/db"
  15. repo_model "code.gitea.io/gitea/models/repo"
  16. user_model "code.gitea.io/gitea/models/user"
  17. "code.gitea.io/gitea/modules/commitstatus"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/timeutil"
  22. "code.gitea.io/gitea/modules/translation"
  23. "xorm.io/builder"
  24. "xorm.io/xorm"
  25. )
  26. // CommitStatus holds a single Status of a single Commit
  27. type CommitStatus struct {
  28. ID int64 `xorm:"pk autoincr"`
  29. Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  30. RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  31. Repo *repo_model.Repository `xorm:"-"`
  32. State commitstatus.CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
  33. SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
  34. TargetURL string `xorm:"TEXT"`
  35. Description string `xorm:"TEXT"`
  36. ContextHash string `xorm:"VARCHAR(64) index"`
  37. Context string `xorm:"TEXT"`
  38. Creator *user_model.User `xorm:"-"`
  39. CreatorID int64
  40. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  41. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  42. }
  43. func init() {
  44. db.RegisterModel(new(CommitStatus))
  45. db.RegisterModel(new(CommitStatusIndex))
  46. }
  47. func postgresGetCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) {
  48. res, err := db.GetEngine(ctx).Query("INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
  49. "VALUES (?,?,1) ON CONFLICT (repo_id, sha) DO UPDATE SET max_index = `commit_status_index`.max_index+1 RETURNING max_index",
  50. repoID, sha)
  51. if err != nil {
  52. return 0, err
  53. }
  54. if len(res) == 0 {
  55. return 0, db.ErrGetResourceIndexFailed
  56. }
  57. return strconv.ParseInt(string(res[0]["max_index"]), 10, 64)
  58. }
  59. func mysqlGetCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) {
  60. if _, err := db.GetEngine(ctx).Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
  61. "VALUES (?,?,1) ON DUPLICATE KEY UPDATE max_index = max_index+1",
  62. repoID, sha); err != nil {
  63. return 0, err
  64. }
  65. var idx int64
  66. _, err := db.GetEngine(ctx).SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ?",
  67. repoID, sha).Get(&idx)
  68. if err != nil {
  69. return 0, err
  70. }
  71. if idx == 0 {
  72. return 0, errors.New("cannot get the correct index")
  73. }
  74. return idx, nil
  75. }
  76. func mssqlGetCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) {
  77. if _, err := db.GetEngine(ctx).Exec(`
  78. MERGE INTO commit_status_index WITH (HOLDLOCK) AS target
  79. USING (SELECT ? AS repo_id, ? AS sha) AS source
  80. (repo_id, sha)
  81. ON target.repo_id = source.repo_id AND target.sha = source.sha
  82. WHEN MATCHED
  83. THEN UPDATE
  84. SET max_index = max_index + 1
  85. WHEN NOT MATCHED
  86. THEN INSERT (repo_id, sha, max_index)
  87. VALUES (?, ?, 1);
  88. `, repoID, sha, repoID, sha); err != nil {
  89. return 0, err
  90. }
  91. var idx int64
  92. _, err := db.GetEngine(ctx).SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ?",
  93. repoID, sha).Get(&idx)
  94. if err != nil {
  95. return 0, err
  96. }
  97. if idx == 0 {
  98. return 0, errors.New("cannot get the correct index")
  99. }
  100. return idx, nil
  101. }
  102. // GetNextCommitStatusIndex retried 3 times to generate a resource index
  103. func GetNextCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) {
  104. _, err := git.NewIDFromString(sha)
  105. if err != nil {
  106. return 0, git.ErrInvalidSHA{SHA: sha}
  107. }
  108. switch {
  109. case setting.Database.Type.IsPostgreSQL():
  110. return postgresGetCommitStatusIndex(ctx, repoID, sha)
  111. case setting.Database.Type.IsMySQL():
  112. return mysqlGetCommitStatusIndex(ctx, repoID, sha)
  113. case setting.Database.Type.IsMSSQL():
  114. return mssqlGetCommitStatusIndex(ctx, repoID, sha)
  115. }
  116. e := db.GetEngine(ctx)
  117. // try to update the max_index to next value, and acquire the write-lock for the record
  118. res, err := e.Exec("UPDATE `commit_status_index` SET max_index=max_index+1 WHERE repo_id=? AND sha=?", repoID, sha)
  119. if err != nil {
  120. return 0, fmt.Errorf("update failed: %w", err)
  121. }
  122. affected, err := res.RowsAffected()
  123. if err != nil {
  124. return 0, err
  125. }
  126. if affected == 0 {
  127. // this slow path is only for the first time of creating a resource index
  128. _, errIns := e.Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) VALUES (?, ?, 0)", repoID, sha)
  129. res, err = e.Exec("UPDATE `commit_status_index` SET max_index=max_index+1 WHERE repo_id=? AND sha=?", repoID, sha)
  130. if err != nil {
  131. return 0, fmt.Errorf("update2 failed: %w", err)
  132. }
  133. affected, err = res.RowsAffected()
  134. if err != nil {
  135. return 0, fmt.Errorf("RowsAffected failed: %w", err)
  136. }
  137. // if the update still can not update any records, the record must not exist and there must be some errors (insert error)
  138. if affected == 0 {
  139. if errIns == nil {
  140. return 0, errors.New("impossible error when GetNextCommitStatusIndex, insert and update both succeeded but no record is updated")
  141. }
  142. return 0, fmt.Errorf("insert failed: %w", errIns)
  143. }
  144. }
  145. // now, the new index is in database (protected by the transaction and write-lock)
  146. var newIdx int64
  147. has, err := e.SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id=? AND sha=?", repoID, sha).Get(&newIdx)
  148. if err != nil {
  149. return 0, fmt.Errorf("select failed: %w", err)
  150. }
  151. if !has {
  152. return 0, errors.New("impossible error when GetNextCommitStatusIndex, upsert succeeded but no record can be selected")
  153. }
  154. return newIdx, nil
  155. }
  156. func (status *CommitStatus) loadRepository(ctx context.Context) (err error) {
  157. if status.Repo == nil {
  158. status.Repo, err = repo_model.GetRepositoryByID(ctx, status.RepoID)
  159. if err != nil {
  160. return fmt.Errorf("getRepositoryByID [%d]: %w", status.RepoID, err)
  161. }
  162. }
  163. return nil
  164. }
  165. func (status *CommitStatus) loadCreator(ctx context.Context) (err error) {
  166. if status.Creator == nil && status.CreatorID > 0 {
  167. status.Creator, err = user_model.GetUserByID(ctx, status.CreatorID)
  168. if err != nil {
  169. return fmt.Errorf("getUserByID [%d]: %w", status.CreatorID, err)
  170. }
  171. }
  172. return nil
  173. }
  174. func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) {
  175. if err := status.loadRepository(ctx); err != nil {
  176. return err
  177. }
  178. return status.loadCreator(ctx)
  179. }
  180. // APIURL returns the absolute APIURL to this commit-status.
  181. func (status *CommitStatus) APIURL(ctx context.Context) string {
  182. _ = status.loadAttributes(ctx)
  183. return status.Repo.APIURL() + "/statuses/" + url.PathEscape(status.SHA)
  184. }
  185. // LocaleString returns the locale string name of the Status
  186. func (status *CommitStatus) LocaleString(lang translation.Locale) string {
  187. return lang.TrString("repo.commitstatus." + status.State.String())
  188. }
  189. // HideActionsURL set `TargetURL` to an empty string if the status comes from Gitea Actions
  190. func (status *CommitStatus) HideActionsURL(ctx context.Context) {
  191. if status.RepoID == 0 {
  192. return
  193. }
  194. if status.Repo == nil {
  195. if err := status.loadRepository(ctx); err != nil {
  196. log.Error("loadRepository: %v", err)
  197. return
  198. }
  199. }
  200. prefix := status.Repo.Link() + "/actions"
  201. if strings.HasPrefix(status.TargetURL, prefix) {
  202. status.TargetURL = ""
  203. }
  204. }
  205. // CalcCommitStatus returns commit status state via some status, the commit statues should order by id desc
  206. func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus {
  207. if len(statuses) == 0 {
  208. return nil
  209. }
  210. states := make(commitstatus.CommitStatusStates, 0, len(statuses))
  211. targetURL := ""
  212. for _, status := range statuses {
  213. states = append(states, status.State)
  214. if status.TargetURL != "" {
  215. targetURL = status.TargetURL
  216. }
  217. }
  218. return &CommitStatus{
  219. RepoID: statuses[0].RepoID,
  220. SHA: statuses[0].SHA,
  221. State: states.Combine(),
  222. TargetURL: targetURL,
  223. }
  224. }
  225. // CommitStatusOptions holds the options for query commit statuses
  226. type CommitStatusOptions struct {
  227. db.ListOptions
  228. RepoID int64
  229. SHA string
  230. State string
  231. SortType string
  232. }
  233. func (opts *CommitStatusOptions) ToConds() builder.Cond {
  234. var cond builder.Cond = builder.Eq{
  235. "repo_id": opts.RepoID,
  236. "sha": opts.SHA,
  237. }
  238. switch opts.State {
  239. case "pending", "success", "error", "failure", "warning":
  240. cond = cond.And(builder.Eq{
  241. "state": opts.State,
  242. })
  243. }
  244. return cond
  245. }
  246. func (opts *CommitStatusOptions) ToOrders() string {
  247. switch opts.SortType {
  248. case "oldest":
  249. return "created_unix ASC"
  250. case "recentupdate":
  251. return "updated_unix DESC"
  252. case "leastupdate":
  253. return "updated_unix ASC"
  254. case "leastindex":
  255. return "`index` DESC"
  256. case "highestindex":
  257. return "`index` ASC"
  258. default:
  259. return "created_unix DESC"
  260. }
  261. }
  262. // CommitStatusIndex represents a table for commit status index
  263. type CommitStatusIndex struct {
  264. ID int64
  265. RepoID int64 `xorm:"unique(repo_sha)"`
  266. SHA string `xorm:"unique(repo_sha)"`
  267. MaxIndex int64 `xorm:"index"`
  268. }
  269. func makeRepoCommitQuery(ctx context.Context, repoID int64, sha string) *xorm.Session {
  270. return db.GetEngine(ctx).Table(&CommitStatus{}).
  271. Where("repo_id = ?", repoID).And("sha = ?", sha)
  272. }
  273. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
  274. func GetLatestCommitStatus(ctx context.Context, repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, error) {
  275. indices := make([]int64, 0, 10)
  276. sess := makeRepoCommitQuery(ctx, repoID, sha).
  277. Select("max( `index` ) as `index`").
  278. GroupBy("context_hash").
  279. OrderBy("max( `index` ) desc")
  280. if !listOptions.IsListAll() {
  281. sess = db.SetSessionPagination(sess, &listOptions)
  282. }
  283. if err := sess.Find(&indices); err != nil {
  284. return nil, err
  285. }
  286. statuses := make([]*CommitStatus, 0, len(indices))
  287. if len(indices) == 0 {
  288. return statuses, nil
  289. }
  290. err := makeRepoCommitQuery(ctx, repoID, sha).And(builder.In("`index`", indices)).Find(&statuses)
  291. return statuses, err
  292. }
  293. func CountLatestCommitStatus(ctx context.Context, repoID int64, sha string) (int64, error) {
  294. return makeRepoCommitQuery(ctx, repoID, sha).
  295. Select("count(context_hash)").
  296. GroupBy("context_hash").
  297. Count()
  298. }
  299. // GetLatestCommitStatusForPairs returns all statuses with a unique context for a given list of repo-sha pairs
  300. func GetLatestCommitStatusForPairs(ctx context.Context, repoSHAs []RepoSHA) (map[int64][]*CommitStatus, error) {
  301. type result struct {
  302. Index int64
  303. RepoID int64
  304. SHA string
  305. }
  306. results := make([]result, 0, len(repoSHAs))
  307. getBase := func() *xorm.Session {
  308. return db.GetEngine(ctx).Table(&CommitStatus{})
  309. }
  310. // Create a disjunction of conditions for each repoID and SHA pair
  311. conds := make([]builder.Cond, 0, len(repoSHAs))
  312. for _, repoSHA := range repoSHAs {
  313. conds = append(conds, builder.Eq{"repo_id": repoSHA.RepoID, "sha": repoSHA.SHA})
  314. }
  315. sess := getBase().Where(builder.Or(conds...)).
  316. Select("max( `index` ) as `index`, repo_id, sha").
  317. GroupBy("context_hash, repo_id, sha").OrderBy("max( `index` ) desc")
  318. err := sess.Find(&results)
  319. if err != nil {
  320. return nil, err
  321. }
  322. repoStatuses := make(map[int64][]*CommitStatus)
  323. if len(results) > 0 {
  324. statuses := make([]*CommitStatus, 0, len(results))
  325. conds = make([]builder.Cond, 0, len(results))
  326. for _, result := range results {
  327. cond := builder.Eq{
  328. "`index`": result.Index,
  329. "repo_id": result.RepoID,
  330. "sha": result.SHA,
  331. }
  332. conds = append(conds, cond)
  333. }
  334. err = getBase().Where(builder.Or(conds...)).Find(&statuses)
  335. if err != nil {
  336. return nil, err
  337. }
  338. // Group the statuses by repo ID
  339. for _, status := range statuses {
  340. repoStatuses[status.RepoID] = append(repoStatuses[status.RepoID], status)
  341. }
  342. }
  343. return repoStatuses, nil
  344. }
  345. // GetLatestCommitStatusForRepoCommitIDs returns all statuses with a unique context for a given list of repo-sha pairs
  346. func GetLatestCommitStatusForRepoCommitIDs(ctx context.Context, repoID int64, commitIDs []string) (map[string][]*CommitStatus, error) {
  347. type result struct {
  348. Index int64
  349. SHA string
  350. }
  351. getBase := func() *xorm.Session {
  352. return db.GetEngine(ctx).Table(&CommitStatus{}).Where("repo_id = ?", repoID)
  353. }
  354. results := make([]result, 0, len(commitIDs))
  355. conds := make([]builder.Cond, 0, len(commitIDs))
  356. for _, sha := range commitIDs {
  357. conds = append(conds, builder.Eq{"sha": sha})
  358. }
  359. sess := getBase().And(builder.Or(conds...)).
  360. Select("max( `index` ) as `index`, sha").
  361. GroupBy("context_hash, sha").OrderBy("max( `index` ) desc")
  362. err := sess.Find(&results)
  363. if err != nil {
  364. return nil, err
  365. }
  366. repoStatuses := make(map[string][]*CommitStatus)
  367. if len(results) > 0 {
  368. statuses := make([]*CommitStatus, 0, len(results))
  369. conds = make([]builder.Cond, 0, len(results))
  370. for _, result := range results {
  371. conds = append(conds, builder.Eq{"`index`": result.Index, "sha": result.SHA})
  372. }
  373. err = getBase().And(builder.Or(conds...)).Find(&statuses)
  374. if err != nil {
  375. return nil, err
  376. }
  377. // Group the statuses by commit
  378. for _, status := range statuses {
  379. repoStatuses[status.SHA] = append(repoStatuses[status.SHA], status)
  380. }
  381. }
  382. return repoStatuses, nil
  383. }
  384. // FindRepoRecentCommitStatusContexts returns repository's recent commit status contexts
  385. func FindRepoRecentCommitStatusContexts(ctx context.Context, repoID int64, before time.Duration) ([]string, error) {
  386. start := timeutil.TimeStampNow().AddDuration(-before)
  387. var contexts []string
  388. if err := db.GetEngine(ctx).Table("commit_status").
  389. Where("repo_id = ?", repoID).And("updated_unix >= ?", start).
  390. Cols("context").Distinct().Find(&contexts); err != nil {
  391. return nil, err
  392. }
  393. return contexts, nil
  394. }
  395. // NewCommitStatusOptions holds options for creating a CommitStatus
  396. type NewCommitStatusOptions struct {
  397. Repo *repo_model.Repository
  398. Creator *user_model.User
  399. SHA git.ObjectID
  400. CommitStatus *CommitStatus
  401. }
  402. // NewCommitStatus save commit statuses into database
  403. func NewCommitStatus(ctx context.Context, opts NewCommitStatusOptions) error {
  404. if opts.Repo == nil {
  405. return fmt.Errorf("NewCommitStatus[nil, %s]: no repository specified", opts.SHA)
  406. }
  407. if opts.Creator == nil {
  408. return fmt.Errorf("NewCommitStatus[%s, %s]: no user specified", opts.Repo.FullName(), opts.SHA)
  409. }
  410. return db.WithTx(ctx, func(ctx context.Context) error {
  411. // Get the next Status Index
  412. idx, err := GetNextCommitStatusIndex(ctx, opts.Repo.ID, opts.SHA.String())
  413. if err != nil {
  414. return fmt.Errorf("generate commit status index failed: %w", err)
  415. }
  416. opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description)
  417. opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context)
  418. opts.CommitStatus.TargetURL = strings.TrimSpace(opts.CommitStatus.TargetURL)
  419. opts.CommitStatus.SHA = opts.SHA.String()
  420. opts.CommitStatus.CreatorID = opts.Creator.ID
  421. opts.CommitStatus.RepoID = opts.Repo.ID
  422. opts.CommitStatus.Index = idx
  423. log.Debug("NewCommitStatus[%s, %s]: %d", opts.Repo.FullName(), opts.SHA, opts.CommitStatus.Index)
  424. opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context)
  425. // Insert new CommitStatus
  426. if err = db.Insert(ctx, opts.CommitStatus); err != nil {
  427. return fmt.Errorf("insert CommitStatus[%s, %s]: %w", opts.Repo.FullName(), opts.SHA, err)
  428. }
  429. return nil
  430. })
  431. }
  432. // SignCommitWithStatuses represents a commit with validation of signature and status state.
  433. type SignCommitWithStatuses struct {
  434. Status *CommitStatus
  435. Statuses []*CommitStatus
  436. *asymkey_model.SignCommit
  437. }
  438. // hashCommitStatusContext hash context
  439. func hashCommitStatusContext(context string) string {
  440. return fmt.Sprintf("%x", sha1.Sum([]byte(context)))
  441. }
  442. // CommitStatusesHideActionsURL hide Gitea Actions urls
  443. func CommitStatusesHideActionsURL(ctx context.Context, statuses []*CommitStatus) {
  444. idToRepos := make(map[int64]*repo_model.Repository)
  445. for _, status := range statuses {
  446. if status == nil {
  447. continue
  448. }
  449. if status.Repo == nil {
  450. status.Repo = idToRepos[status.RepoID]
  451. }
  452. status.HideActionsURL(ctx)
  453. idToRepos[status.RepoID] = status.Repo
  454. }
  455. }