Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

commit_status.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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:"char(40) 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. if !git.IsValidSHAPattern(sha) {
  105. return 0, git.ErrInvalidSHA{SHA: sha}
  106. }
  107. switch {
  108. case setting.Database.Type.IsPostgreSQL():
  109. return postgresGetCommitStatusIndex(ctx, repoID, sha)
  110. case setting.Database.Type.IsMySQL():
  111. return mysqlGetCommitStatusIndex(ctx, repoID, sha)
  112. case setting.Database.Type.IsMSSQL():
  113. return mssqlGetCommitStatusIndex(ctx, repoID, sha)
  114. }
  115. e := db.GetEngine(ctx)
  116. // try to update the max_index to next value, and acquire the write-lock for the record
  117. res, err := e.Exec("UPDATE `commit_status_index` SET max_index=max_index+1 WHERE repo_id=? AND sha=?", repoID, sha)
  118. if err != nil {
  119. return 0, fmt.Errorf("update failed: %w", err)
  120. }
  121. affected, err := res.RowsAffected()
  122. if err != nil {
  123. return 0, err
  124. }
  125. if affected == 0 {
  126. // this slow path is only for the first time of creating a resource index
  127. _, errIns := e.Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) VALUES (?, ?, 0)", repoID, sha)
  128. res, err = e.Exec("UPDATE `commit_status_index` SET max_index=max_index+1 WHERE repo_id=? AND sha=?", repoID, sha)
  129. if err != nil {
  130. return 0, fmt.Errorf("update2 failed: %w", err)
  131. }
  132. affected, err = res.RowsAffected()
  133. if err != nil {
  134. return 0, fmt.Errorf("RowsAffected failed: %w", err)
  135. }
  136. // if the update still can not update any records, the record must not exist and there must be some errors (insert error)
  137. if affected == 0 {
  138. if errIns == nil {
  139. return 0, errors.New("impossible error when GetNextCommitStatusIndex, insert and update both succeeded but no record is updated")
  140. }
  141. return 0, fmt.Errorf("insert failed: %w", errIns)
  142. }
  143. }
  144. // now, the new index is in database (protected by the transaction and write-lock)
  145. var newIdx int64
  146. has, err := e.SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id=? AND sha=?", repoID, sha).Get(&newIdx)
  147. if err != nil {
  148. return 0, fmt.Errorf("select failed: %w", err)
  149. }
  150. if !has {
  151. return 0, errors.New("impossible error when GetNextCommitStatusIndex, upsert succeeded but no record can be selected")
  152. }
  153. return newIdx, nil
  154. }
  155. func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) {
  156. if status.Repo == nil {
  157. status.Repo, err = repo_model.GetRepositoryByID(ctx, status.RepoID)
  158. if err != nil {
  159. return fmt.Errorf("getRepositoryByID [%d]: %w", status.RepoID, err)
  160. }
  161. }
  162. if status.Creator == nil && status.CreatorID > 0 {
  163. status.Creator, err = user_model.GetUserByID(ctx, status.CreatorID)
  164. if err != nil {
  165. return fmt.Errorf("getUserByID [%d]: %w", status.CreatorID, err)
  166. }
  167. }
  168. return nil
  169. }
  170. // APIURL returns the absolute APIURL to this commit-status.
  171. func (status *CommitStatus) APIURL(ctx context.Context) string {
  172. _ = status.loadAttributes(ctx)
  173. return status.Repo.APIURL() + "/statuses/" + url.PathEscape(status.SHA)
  174. }
  175. // LocaleString returns the locale string name of the Status
  176. func (status *CommitStatus) LocaleString(lang translation.Locale) string {
  177. return lang.Tr("repo.commitstatus." + status.State.String())
  178. }
  179. // CalcCommitStatus returns commit status state via some status, the commit statues should order by id desc
  180. func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus {
  181. var lastStatus *CommitStatus
  182. state := api.CommitStatusSuccess
  183. for _, status := range statuses {
  184. if status.State.NoBetterThan(state) {
  185. state = status.State
  186. lastStatus = status
  187. }
  188. }
  189. if lastStatus == nil {
  190. if len(statuses) > 0 {
  191. lastStatus = statuses[0]
  192. } else {
  193. lastStatus = &CommitStatus{}
  194. }
  195. }
  196. return lastStatus
  197. }
  198. // CommitStatusOptions holds the options for query commit statuses
  199. type CommitStatusOptions struct {
  200. db.ListOptions
  201. State string
  202. SortType string
  203. }
  204. // GetCommitStatuses returns all statuses for a given commit.
  205. func GetCommitStatuses(ctx context.Context, repo *repo_model.Repository, sha string, opts *CommitStatusOptions) ([]*CommitStatus, int64, error) {
  206. if opts.Page <= 0 {
  207. opts.Page = 1
  208. }
  209. if opts.PageSize <= 0 {
  210. opts.Page = setting.ItemsPerPage
  211. }
  212. countSession := listCommitStatusesStatement(ctx, repo, sha, opts)
  213. countSession = db.SetSessionPagination(countSession, opts)
  214. maxResults, err := countSession.Count(new(CommitStatus))
  215. if err != nil {
  216. log.Error("Count PRs: %v", err)
  217. return nil, maxResults, err
  218. }
  219. statuses := make([]*CommitStatus, 0, opts.PageSize)
  220. findSession := listCommitStatusesStatement(ctx, repo, sha, opts)
  221. findSession = db.SetSessionPagination(findSession, opts)
  222. sortCommitStatusesSession(findSession, opts.SortType)
  223. return statuses, maxResults, findSession.Find(&statuses)
  224. }
  225. func listCommitStatusesStatement(ctx context.Context, repo *repo_model.Repository, sha string, opts *CommitStatusOptions) *xorm.Session {
  226. sess := db.GetEngine(ctx).Where("repo_id = ?", repo.ID).And("sha = ?", sha)
  227. switch opts.State {
  228. case "pending", "success", "error", "failure", "warning":
  229. sess.And("state = ?", opts.State)
  230. }
  231. return sess
  232. }
  233. func sortCommitStatusesSession(sess *xorm.Session, sortType string) {
  234. switch sortType {
  235. case "oldest":
  236. sess.Asc("created_unix")
  237. case "recentupdate":
  238. sess.Desc("updated_unix")
  239. case "leastupdate":
  240. sess.Asc("updated_unix")
  241. case "leastindex":
  242. sess.Desc("index")
  243. case "highestindex":
  244. sess.Asc("index")
  245. default:
  246. sess.Desc("created_unix")
  247. }
  248. }
  249. // CommitStatusIndex represents a table for commit status index
  250. type CommitStatusIndex struct {
  251. ID int64
  252. RepoID int64 `xorm:"unique(repo_sha)"`
  253. SHA string `xorm:"unique(repo_sha)"`
  254. MaxIndex int64 `xorm:"index"`
  255. }
  256. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
  257. func GetLatestCommitStatus(ctx context.Context, repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, int64, error) {
  258. ids := make([]int64, 0, 10)
  259. sess := db.GetEngine(ctx).Table(&CommitStatus{}).
  260. Where("repo_id = ?", repoID).And("sha = ?", sha).
  261. Select("max( id ) as id").
  262. GroupBy("context_hash").OrderBy("max( id ) desc")
  263. if !listOptions.IsListAll() {
  264. sess = db.SetSessionPagination(sess, &listOptions)
  265. }
  266. count, err := sess.FindAndCount(&ids)
  267. if err != nil {
  268. return nil, count, err
  269. }
  270. statuses := make([]*CommitStatus, 0, len(ids))
  271. if len(ids) == 0 {
  272. return statuses, count, nil
  273. }
  274. return statuses, count, db.GetEngine(ctx).In("id", ids).Find(&statuses)
  275. }
  276. // GetLatestCommitStatusForPairs returns all statuses with a unique context for a given list of repo-sha pairs
  277. func GetLatestCommitStatusForPairs(ctx context.Context, repoIDsToLatestCommitSHAs map[int64]string, listOptions db.ListOptions) (map[int64][]*CommitStatus, error) {
  278. type result struct {
  279. ID int64
  280. RepoID int64
  281. }
  282. results := make([]result, 0, len(repoIDsToLatestCommitSHAs))
  283. sess := db.GetEngine(ctx).Table(&CommitStatus{})
  284. // Create a disjunction of conditions for each repoID and SHA pair
  285. conds := make([]builder.Cond, 0, len(repoIDsToLatestCommitSHAs))
  286. for repoID, sha := range repoIDsToLatestCommitSHAs {
  287. conds = append(conds, builder.Eq{"repo_id": repoID, "sha": sha})
  288. }
  289. sess = sess.Where(builder.Or(conds...)).
  290. Select("max( id ) as id, repo_id").
  291. GroupBy("context_hash, repo_id").OrderBy("max( id ) desc")
  292. sess = db.SetSessionPagination(sess, &listOptions)
  293. err := sess.Find(&results)
  294. if err != nil {
  295. return nil, err
  296. }
  297. ids := make([]int64, 0, len(results))
  298. repoStatuses := make(map[int64][]*CommitStatus)
  299. for _, result := range results {
  300. ids = append(ids, result.ID)
  301. }
  302. statuses := make([]*CommitStatus, 0, len(ids))
  303. if len(ids) > 0 {
  304. err = db.GetEngine(ctx).In("id", ids).Find(&statuses)
  305. if err != nil {
  306. return nil, err
  307. }
  308. // Group the statuses by repo ID
  309. for _, status := range statuses {
  310. repoStatuses[status.RepoID] = append(repoStatuses[status.RepoID], status)
  311. }
  312. }
  313. return repoStatuses, nil
  314. }
  315. // GetLatestCommitStatusForRepoCommitIDs returns all statuses with a unique context for a given list of repo-sha pairs
  316. func GetLatestCommitStatusForRepoCommitIDs(ctx context.Context, repoID int64, commitIDs []string) (map[string][]*CommitStatus, error) {
  317. type result struct {
  318. ID int64
  319. Sha string
  320. }
  321. results := make([]result, 0, len(commitIDs))
  322. sess := db.GetEngine(ctx).Table(&CommitStatus{})
  323. // Create a disjunction of conditions for each repoID and SHA pair
  324. conds := make([]builder.Cond, 0, len(commitIDs))
  325. for _, sha := range commitIDs {
  326. conds = append(conds, builder.Eq{"sha": sha})
  327. }
  328. sess = sess.Where(builder.Eq{"repo_id": repoID}.And(builder.Or(conds...))).
  329. Select("max( id ) as id, sha").
  330. GroupBy("context_hash, sha").OrderBy("max( id ) desc")
  331. err := sess.Find(&results)
  332. if err != nil {
  333. return nil, err
  334. }
  335. ids := make([]int64, 0, len(results))
  336. repoStatuses := make(map[string][]*CommitStatus)
  337. for _, result := range results {
  338. ids = append(ids, result.ID)
  339. }
  340. statuses := make([]*CommitStatus, 0, len(ids))
  341. if len(ids) > 0 {
  342. err = db.GetEngine(ctx).In("id", ids).Find(&statuses)
  343. if err != nil {
  344. return nil, err
  345. }
  346. // Group the statuses by repo ID
  347. for _, status := range statuses {
  348. repoStatuses[status.SHA] = append(repoStatuses[status.SHA], status)
  349. }
  350. }
  351. return repoStatuses, nil
  352. }
  353. // FindRepoRecentCommitStatusContexts returns repository's recent commit status contexts
  354. func FindRepoRecentCommitStatusContexts(ctx context.Context, repoID int64, before time.Duration) ([]string, error) {
  355. start := timeutil.TimeStampNow().AddDuration(-before)
  356. ids := make([]int64, 0, 10)
  357. if err := db.GetEngine(ctx).Table("commit_status").
  358. Where("repo_id = ?", repoID).
  359. And("updated_unix >= ?", start).
  360. Select("max( id ) as id").
  361. GroupBy("context_hash").OrderBy("max( id ) desc").
  362. Find(&ids); err != nil {
  363. return nil, err
  364. }
  365. contexts := make([]string, 0, len(ids))
  366. if len(ids) == 0 {
  367. return contexts, nil
  368. }
  369. return contexts, db.GetEngine(ctx).Select("context").Table("commit_status").In("id", ids).Find(&contexts)
  370. }
  371. // NewCommitStatusOptions holds options for creating a CommitStatus
  372. type NewCommitStatusOptions struct {
  373. Repo *repo_model.Repository
  374. Creator *user_model.User
  375. SHA string
  376. CommitStatus *CommitStatus
  377. }
  378. // NewCommitStatus save commit statuses into database
  379. func NewCommitStatus(ctx context.Context, opts NewCommitStatusOptions) error {
  380. if opts.Repo == nil {
  381. return fmt.Errorf("NewCommitStatus[nil, %s]: no repository specified", opts.SHA)
  382. }
  383. repoPath := opts.Repo.RepoPath()
  384. if opts.Creator == nil {
  385. return fmt.Errorf("NewCommitStatus[%s, %s]: no user specified", repoPath, opts.SHA)
  386. }
  387. if _, err := git.NewIDFromString(opts.SHA); err != nil {
  388. return fmt.Errorf("NewCommitStatus[%s, %s]: invalid sha: %w", repoPath, opts.SHA, err)
  389. }
  390. ctx, committer, err := db.TxContext(ctx)
  391. if err != nil {
  392. return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %w", opts.Repo.ID, opts.Creator.ID, opts.SHA, err)
  393. }
  394. defer committer.Close()
  395. // Get the next Status Index
  396. idx, err := GetNextCommitStatusIndex(ctx, opts.Repo.ID, opts.SHA)
  397. if err != nil {
  398. return fmt.Errorf("generate commit status index failed: %w", err)
  399. }
  400. opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description)
  401. opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context)
  402. opts.CommitStatus.TargetURL = strings.TrimSpace(opts.CommitStatus.TargetURL)
  403. opts.CommitStatus.SHA = opts.SHA
  404. opts.CommitStatus.CreatorID = opts.Creator.ID
  405. opts.CommitStatus.RepoID = opts.Repo.ID
  406. opts.CommitStatus.Index = idx
  407. log.Debug("NewCommitStatus[%s, %s]: %d", repoPath, opts.SHA, opts.CommitStatus.Index)
  408. opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context)
  409. // Insert new CommitStatus
  410. if _, err = db.GetEngine(ctx).Insert(opts.CommitStatus); err != nil {
  411. return fmt.Errorf("insert CommitStatus[%s, %s]: %w", repoPath, opts.SHA, err)
  412. }
  413. return committer.Commit()
  414. }
  415. // SignCommitWithStatuses represents a commit with validation of signature and status state.
  416. type SignCommitWithStatuses struct {
  417. Status *CommitStatus
  418. Statuses []*CommitStatus
  419. *asymkey_model.SignCommit
  420. }
  421. // ParseCommitsWithStatus checks commits latest statuses and calculates its worst status state
  422. func ParseCommitsWithStatus(ctx context.Context, oldCommits []*asymkey_model.SignCommit, repo *repo_model.Repository) []*SignCommitWithStatuses {
  423. newCommits := make([]*SignCommitWithStatuses, 0, len(oldCommits))
  424. for _, c := range oldCommits {
  425. commit := &SignCommitWithStatuses{
  426. SignCommit: c,
  427. }
  428. statuses, _, err := GetLatestCommitStatus(ctx, repo.ID, commit.ID.String(), db.ListOptions{})
  429. if err != nil {
  430. log.Error("GetLatestCommitStatus: %v", err)
  431. } else {
  432. commit.Statuses = statuses
  433. commit.Status = CalcCommitStatus(statuses)
  434. }
  435. newCommits = append(newCommits, commit)
  436. }
  437. return newCommits
  438. }
  439. // hashCommitStatusContext hash context
  440. func hashCommitStatusContext(context string) string {
  441. return fmt.Sprintf("%x", sha1.Sum([]byte(context)))
  442. }
  443. // ConvertFromGitCommit converts git commits into SignCommitWithStatuses
  444. func ConvertFromGitCommit(ctx context.Context, commits []*git.Commit, repo *repo_model.Repository) []*SignCommitWithStatuses {
  445. return ParseCommitsWithStatus(ctx,
  446. asymkey_model.ParseCommitsWithSignature(
  447. ctx,
  448. user_model.ValidateCommitsWithEmails(ctx, commits),
  449. repo.GetTrustModel(),
  450. func(user *user_model.User) (bool, error) {
  451. return repo_model.IsOwnerMemberCollaborator(ctx, repo, user.ID)
  452. },
  453. ),
  454. repo,
  455. )
  456. }