You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

commit_status.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. api "code.gitea.io/gitea/modules/structs"
  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 api.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) loadAttributes(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. if status.Creator == nil && status.CreatorID > 0 {
  164. status.Creator, err = user_model.GetUserByID(ctx, status.CreatorID)
  165. if err != nil {
  166. return fmt.Errorf("getUserByID [%d]: %w", status.CreatorID, err)
  167. }
  168. }
  169. return nil
  170. }
  171. // APIURL returns the absolute APIURL to this commit-status.
  172. func (status *CommitStatus) APIURL(ctx context.Context) string {
  173. _ = status.loadAttributes(ctx)
  174. return status.Repo.APIURL() + "/statuses/" + url.PathEscape(status.SHA)
  175. }
  176. // LocaleString returns the locale string name of the Status
  177. func (status *CommitStatus) LocaleString(lang translation.Locale) string {
  178. return lang.TrString("repo.commitstatus." + status.State.String())
  179. }
  180. // CalcCommitStatus returns commit status state via some status, the commit statues should order by id desc
  181. func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus {
  182. var lastStatus *CommitStatus
  183. state := api.CommitStatusSuccess
  184. for _, status := range statuses {
  185. if status.State.NoBetterThan(state) {
  186. state = status.State
  187. lastStatus = status
  188. }
  189. }
  190. if lastStatus == nil {
  191. if len(statuses) > 0 {
  192. lastStatus = statuses[0]
  193. } else {
  194. lastStatus = &CommitStatus{}
  195. }
  196. }
  197. return lastStatus
  198. }
  199. // CommitStatusOptions holds the options for query commit statuses
  200. type CommitStatusOptions struct {
  201. db.ListOptions
  202. RepoID int64
  203. SHA string
  204. State string
  205. SortType string
  206. }
  207. func (opts *CommitStatusOptions) ToConds() builder.Cond {
  208. var cond builder.Cond = builder.Eq{
  209. "repo_id": opts.RepoID,
  210. "sha": opts.SHA,
  211. }
  212. switch opts.State {
  213. case "pending", "success", "error", "failure", "warning":
  214. cond = cond.And(builder.Eq{
  215. "state": opts.State,
  216. })
  217. }
  218. return cond
  219. }
  220. func (opts *CommitStatusOptions) ToOrders() string {
  221. switch opts.SortType {
  222. case "oldest":
  223. return "created_unix ASC"
  224. case "recentupdate":
  225. return "updated_unix DESC"
  226. case "leastupdate":
  227. return "updated_unix ASC"
  228. case "leastindex":
  229. return "`index` DESC"
  230. case "highestindex":
  231. return "`index` ASC"
  232. default:
  233. return "created_unix DESC"
  234. }
  235. }
  236. // CommitStatusIndex represents a table for commit status index
  237. type CommitStatusIndex struct {
  238. ID int64
  239. RepoID int64 `xorm:"unique(repo_sha)"`
  240. SHA string `xorm:"unique(repo_sha)"`
  241. MaxIndex int64 `xorm:"index"`
  242. }
  243. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
  244. func GetLatestCommitStatus(ctx context.Context, repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, int64, error) {
  245. getBase := func() *xorm.Session {
  246. return db.GetEngine(ctx).Table(&CommitStatus{}).
  247. Where("repo_id = ?", repoID).And("sha = ?", sha)
  248. }
  249. indices := make([]int64, 0, 10)
  250. sess := getBase().Select("max( `index` ) as `index`").
  251. GroupBy("context_hash").OrderBy("max( `index` ) desc")
  252. if !listOptions.IsListAll() {
  253. sess = db.SetSessionPagination(sess, &listOptions)
  254. }
  255. count, err := sess.FindAndCount(&indices)
  256. if err != nil {
  257. return nil, count, err
  258. }
  259. statuses := make([]*CommitStatus, 0, len(indices))
  260. if len(indices) == 0 {
  261. return statuses, count, nil
  262. }
  263. return statuses, count, getBase().And(builder.In("`index`", indices)).Find(&statuses)
  264. }
  265. // GetLatestCommitStatusForPairs returns all statuses with a unique context for a given list of repo-sha pairs
  266. func GetLatestCommitStatusForPairs(ctx context.Context, repoSHAs []RepoSHA) (map[int64][]*CommitStatus, error) {
  267. type result struct {
  268. Index int64
  269. RepoID int64
  270. SHA string
  271. }
  272. results := make([]result, 0, len(repoSHAs))
  273. getBase := func() *xorm.Session {
  274. return db.GetEngine(ctx).Table(&CommitStatus{})
  275. }
  276. // Create a disjunction of conditions for each repoID and SHA pair
  277. conds := make([]builder.Cond, 0, len(repoSHAs))
  278. for _, repoSHA := range repoSHAs {
  279. conds = append(conds, builder.Eq{"repo_id": repoSHA.RepoID, "sha": repoSHA.SHA})
  280. }
  281. sess := getBase().Where(builder.Or(conds...)).
  282. Select("max( `index` ) as `index`, repo_id, sha").
  283. GroupBy("context_hash, repo_id, sha").OrderBy("max( `index` ) desc")
  284. err := sess.Find(&results)
  285. if err != nil {
  286. return nil, err
  287. }
  288. repoStatuses := make(map[int64][]*CommitStatus)
  289. if len(results) > 0 {
  290. statuses := make([]*CommitStatus, 0, len(results))
  291. conds = make([]builder.Cond, 0, len(results))
  292. for _, result := range results {
  293. cond := builder.Eq{
  294. "`index`": result.Index,
  295. "repo_id": result.RepoID,
  296. "sha": result.SHA,
  297. }
  298. conds = append(conds, cond)
  299. }
  300. err = getBase().Where(builder.Or(conds...)).Find(&statuses)
  301. if err != nil {
  302. return nil, err
  303. }
  304. // Group the statuses by repo ID
  305. for _, status := range statuses {
  306. repoStatuses[status.RepoID] = append(repoStatuses[status.RepoID], status)
  307. }
  308. }
  309. return repoStatuses, nil
  310. }
  311. // GetLatestCommitStatusForRepoCommitIDs returns all statuses with a unique context for a given list of repo-sha pairs
  312. func GetLatestCommitStatusForRepoCommitIDs(ctx context.Context, repoID int64, commitIDs []string) (map[string][]*CommitStatus, error) {
  313. type result struct {
  314. Index int64
  315. SHA string
  316. }
  317. getBase := func() *xorm.Session {
  318. return db.GetEngine(ctx).Table(&CommitStatus{}).Where("repo_id = ?", repoID)
  319. }
  320. results := make([]result, 0, len(commitIDs))
  321. conds := make([]builder.Cond, 0, len(commitIDs))
  322. for _, sha := range commitIDs {
  323. conds = append(conds, builder.Eq{"sha": sha})
  324. }
  325. sess := getBase().And(builder.Or(conds...)).
  326. Select("max( `index` ) as `index`, sha").
  327. GroupBy("context_hash, sha").OrderBy("max( `index` ) desc")
  328. err := sess.Find(&results)
  329. if err != nil {
  330. return nil, err
  331. }
  332. repoStatuses := make(map[string][]*CommitStatus)
  333. if len(results) > 0 {
  334. statuses := make([]*CommitStatus, 0, len(results))
  335. conds = make([]builder.Cond, 0, len(results))
  336. for _, result := range results {
  337. conds = append(conds, builder.Eq{"`index`": result.Index, "sha": result.SHA})
  338. }
  339. err = getBase().And(builder.Or(conds...)).Find(&statuses)
  340. if err != nil {
  341. return nil, err
  342. }
  343. // Group the statuses by commit
  344. for _, status := range statuses {
  345. repoStatuses[status.SHA] = append(repoStatuses[status.SHA], status)
  346. }
  347. }
  348. return repoStatuses, nil
  349. }
  350. // FindRepoRecentCommitStatusContexts returns repository's recent commit status contexts
  351. func FindRepoRecentCommitStatusContexts(ctx context.Context, repoID int64, before time.Duration) ([]string, error) {
  352. start := timeutil.TimeStampNow().AddDuration(-before)
  353. var contexts []string
  354. if err := db.GetEngine(ctx).Table("commit_status").
  355. Where("repo_id = ?", repoID).And("updated_unix >= ?", start).
  356. Cols("context").Distinct().Find(&contexts); err != nil {
  357. return nil, err
  358. }
  359. return contexts, nil
  360. }
  361. // NewCommitStatusOptions holds options for creating a CommitStatus
  362. type NewCommitStatusOptions struct {
  363. Repo *repo_model.Repository
  364. Creator *user_model.User
  365. SHA git.ObjectID
  366. CommitStatus *CommitStatus
  367. }
  368. // NewCommitStatus save commit statuses into database
  369. func NewCommitStatus(ctx context.Context, opts NewCommitStatusOptions) error {
  370. if opts.Repo == nil {
  371. return fmt.Errorf("NewCommitStatus[nil, %s]: no repository specified", opts.SHA)
  372. }
  373. repoPath := opts.Repo.RepoPath()
  374. if opts.Creator == nil {
  375. return fmt.Errorf("NewCommitStatus[%s, %s]: no user specified", repoPath, opts.SHA)
  376. }
  377. ctx, committer, err := db.TxContext(ctx)
  378. if err != nil {
  379. return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %w", opts.Repo.ID, opts.Creator.ID, opts.SHA, err)
  380. }
  381. defer committer.Close()
  382. // Get the next Status Index
  383. idx, err := GetNextCommitStatusIndex(ctx, opts.Repo.ID, opts.SHA.String())
  384. if err != nil {
  385. return fmt.Errorf("generate commit status index failed: %w", err)
  386. }
  387. opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description)
  388. opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context)
  389. opts.CommitStatus.TargetURL = strings.TrimSpace(opts.CommitStatus.TargetURL)
  390. opts.CommitStatus.SHA = opts.SHA.String()
  391. opts.CommitStatus.CreatorID = opts.Creator.ID
  392. opts.CommitStatus.RepoID = opts.Repo.ID
  393. opts.CommitStatus.Index = idx
  394. log.Debug("NewCommitStatus[%s, %s]: %d", repoPath, opts.SHA, opts.CommitStatus.Index)
  395. opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context)
  396. // Insert new CommitStatus
  397. if _, err = db.GetEngine(ctx).Insert(opts.CommitStatus); err != nil {
  398. return fmt.Errorf("insert CommitStatus[%s, %s]: %w", repoPath, opts.SHA, err)
  399. }
  400. return committer.Commit()
  401. }
  402. // SignCommitWithStatuses represents a commit with validation of signature and status state.
  403. type SignCommitWithStatuses struct {
  404. Status *CommitStatus
  405. Statuses []*CommitStatus
  406. *asymkey_model.SignCommit
  407. }
  408. // ParseCommitsWithStatus checks commits latest statuses and calculates its worst status state
  409. func ParseCommitsWithStatus(ctx context.Context, oldCommits []*asymkey_model.SignCommit, repo *repo_model.Repository) []*SignCommitWithStatuses {
  410. newCommits := make([]*SignCommitWithStatuses, 0, len(oldCommits))
  411. for _, c := range oldCommits {
  412. commit := &SignCommitWithStatuses{
  413. SignCommit: c,
  414. }
  415. statuses, _, err := GetLatestCommitStatus(ctx, repo.ID, commit.ID.String(), db.ListOptions{})
  416. if err != nil {
  417. log.Error("GetLatestCommitStatus: %v", err)
  418. } else {
  419. commit.Statuses = statuses
  420. commit.Status = CalcCommitStatus(statuses)
  421. }
  422. newCommits = append(newCommits, commit)
  423. }
  424. return newCommits
  425. }
  426. // hashCommitStatusContext hash context
  427. func hashCommitStatusContext(context string) string {
  428. return fmt.Sprintf("%x", sha1.Sum([]byte(context)))
  429. }
  430. // ConvertFromGitCommit converts git commits into SignCommitWithStatuses
  431. func ConvertFromGitCommit(ctx context.Context, commits []*git.Commit, repo *repo_model.Repository) []*SignCommitWithStatuses {
  432. return ParseCommitsWithStatus(ctx,
  433. asymkey_model.ParseCommitsWithSignature(
  434. ctx,
  435. user_model.ValidateCommitsWithEmails(ctx, commits),
  436. repo.GetTrustModel(),
  437. func(user *user_model.User) (bool, error) {
  438. return repo_model.IsOwnerMemberCollaborator(ctx, repo, user.ID)
  439. },
  440. ),
  441. repo,
  442. )
  443. }