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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. // Copyright 2017 Gitea. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "context"
  7. "crypto/sha1"
  8. "fmt"
  9. "net/url"
  10. "strings"
  11. "time"
  12. asymkey_model "code.gitea.io/gitea/models/asymkey"
  13. "code.gitea.io/gitea/models/db"
  14. repo_model "code.gitea.io/gitea/models/repo"
  15. user_model "code.gitea.io/gitea/models/user"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. api "code.gitea.io/gitea/modules/structs"
  19. "code.gitea.io/gitea/modules/timeutil"
  20. "xorm.io/xorm"
  21. )
  22. // CommitStatus holds a single Status of a single Commit
  23. type CommitStatus struct {
  24. ID int64 `xorm:"pk autoincr"`
  25. Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  26. RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  27. Repo *repo_model.Repository `xorm:"-"`
  28. State api.CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
  29. SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
  30. TargetURL string `xorm:"TEXT"`
  31. Description string `xorm:"TEXT"`
  32. ContextHash string `xorm:"char(40) index"`
  33. Context string `xorm:"TEXT"`
  34. Creator *user_model.User `xorm:"-"`
  35. CreatorID int64
  36. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  37. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  38. }
  39. func init() {
  40. db.RegisterModel(new(CommitStatus))
  41. db.RegisterModel(new(CommitStatusIndex))
  42. }
  43. // upsertCommitStatusIndex the function will not return until it acquires the lock or receives an error.
  44. func upsertCommitStatusIndex(ctx context.Context, repoID int64, sha string) (err error) {
  45. // An atomic UPSERT operation (INSERT/UPDATE) is the only operation
  46. // that ensures that the key is actually locked.
  47. switch {
  48. case setting.Database.UseSQLite3 || setting.Database.UsePostgreSQL:
  49. _, err = db.Exec(ctx, "INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
  50. "VALUES (?,?,1) ON CONFLICT (repo_id,sha) DO UPDATE SET max_index = `commit_status_index`.max_index+1",
  51. repoID, sha)
  52. case setting.Database.UseMySQL:
  53. _, err = db.Exec(ctx, "INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
  54. "VALUES (?,?,1) ON DUPLICATE KEY UPDATE max_index = max_index+1",
  55. repoID, sha)
  56. case setting.Database.UseMSSQL:
  57. // https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/
  58. _, err = db.Exec(ctx, "MERGE `commit_status_index` WITH (HOLDLOCK) as target "+
  59. "USING (SELECT ? AS repo_id, ? AS sha) AS src "+
  60. "ON src.repo_id = target.repo_id AND src.sha = target.sha "+
  61. "WHEN MATCHED THEN UPDATE SET target.max_index = target.max_index+1 "+
  62. "WHEN NOT MATCHED THEN INSERT (repo_id, sha, max_index) "+
  63. "VALUES (src.repo_id, src.sha, 1);",
  64. repoID, sha)
  65. default:
  66. return fmt.Errorf("database type not supported")
  67. }
  68. return
  69. }
  70. // GetNextCommitStatusIndex retried 3 times to generate a resource index
  71. func GetNextCommitStatusIndex(repoID int64, sha string) (int64, error) {
  72. for i := 0; i < db.MaxDupIndexAttempts; i++ {
  73. idx, err := getNextCommitStatusIndex(repoID, sha)
  74. if err == db.ErrResouceOutdated {
  75. continue
  76. }
  77. if err != nil {
  78. return 0, err
  79. }
  80. return idx, nil
  81. }
  82. return 0, db.ErrGetResourceIndexFailed
  83. }
  84. // getNextCommitStatusIndex return the next index
  85. func getNextCommitStatusIndex(repoID int64, sha string) (int64, error) {
  86. ctx, commiter, err := db.TxContext()
  87. if err != nil {
  88. return 0, err
  89. }
  90. defer commiter.Close()
  91. var preIdx int64
  92. _, err = db.GetEngine(ctx).SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ?", repoID, sha).Get(&preIdx)
  93. if err != nil {
  94. return 0, err
  95. }
  96. if err := upsertCommitStatusIndex(ctx, repoID, sha); err != nil {
  97. return 0, err
  98. }
  99. var curIdx int64
  100. has, err := db.GetEngine(ctx).SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ? AND max_index=?", repoID, sha, preIdx+1).Get(&curIdx)
  101. if err != nil {
  102. return 0, err
  103. }
  104. if !has {
  105. return 0, db.ErrResouceOutdated
  106. }
  107. if err := commiter.Commit(); err != nil {
  108. return 0, err
  109. }
  110. return curIdx, nil
  111. }
  112. func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) {
  113. if status.Repo == nil {
  114. status.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, status.RepoID)
  115. if err != nil {
  116. return fmt.Errorf("getRepositoryByID [%d]: %v", status.RepoID, err)
  117. }
  118. }
  119. if status.Creator == nil && status.CreatorID > 0 {
  120. status.Creator, err = user_model.GetUserByIDCtx(ctx, status.CreatorID)
  121. if err != nil {
  122. return fmt.Errorf("getUserByID [%d]: %v", status.CreatorID, err)
  123. }
  124. }
  125. return nil
  126. }
  127. // APIURL returns the absolute APIURL to this commit-status.
  128. func (status *CommitStatus) APIURL() string {
  129. _ = status.loadAttributes(db.DefaultContext)
  130. return status.Repo.APIURL() + "/statuses/" + url.PathEscape(status.SHA)
  131. }
  132. // CalcCommitStatus returns commit status state via some status, the commit statues should order by id desc
  133. func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus {
  134. var lastStatus *CommitStatus
  135. var state api.CommitStatusState
  136. for _, status := range statuses {
  137. if status.State.NoBetterThan(state) {
  138. state = status.State
  139. lastStatus = status
  140. }
  141. }
  142. if lastStatus == nil {
  143. if len(statuses) > 0 {
  144. lastStatus = statuses[0]
  145. } else {
  146. lastStatus = &CommitStatus{}
  147. }
  148. }
  149. return lastStatus
  150. }
  151. // CommitStatusOptions holds the options for query commit statuses
  152. type CommitStatusOptions struct {
  153. db.ListOptions
  154. State string
  155. SortType string
  156. }
  157. // GetCommitStatuses returns all statuses for a given commit.
  158. func GetCommitStatuses(repo *repo_model.Repository, sha string, opts *CommitStatusOptions) ([]*CommitStatus, int64, error) {
  159. if opts.Page <= 0 {
  160. opts.Page = 1
  161. }
  162. if opts.PageSize <= 0 {
  163. opts.Page = ItemsPerPage
  164. }
  165. countSession := listCommitStatusesStatement(repo, sha, opts)
  166. countSession = db.SetSessionPagination(countSession, opts)
  167. maxResults, err := countSession.Count(new(CommitStatus))
  168. if err != nil {
  169. log.Error("Count PRs: %v", err)
  170. return nil, maxResults, err
  171. }
  172. statuses := make([]*CommitStatus, 0, opts.PageSize)
  173. findSession := listCommitStatusesStatement(repo, sha, opts)
  174. findSession = db.SetSessionPagination(findSession, opts)
  175. sortCommitStatusesSession(findSession, opts.SortType)
  176. return statuses, maxResults, findSession.Find(&statuses)
  177. }
  178. func listCommitStatusesStatement(repo *repo_model.Repository, sha string, opts *CommitStatusOptions) *xorm.Session {
  179. sess := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).And("sha = ?", sha)
  180. switch opts.State {
  181. case "pending", "success", "error", "failure", "warning":
  182. sess.And("state = ?", opts.State)
  183. }
  184. return sess
  185. }
  186. func sortCommitStatusesSession(sess *xorm.Session, sortType string) {
  187. switch sortType {
  188. case "oldest":
  189. sess.Asc("created_unix")
  190. case "recentupdate":
  191. sess.Desc("updated_unix")
  192. case "leastupdate":
  193. sess.Asc("updated_unix")
  194. case "leastindex":
  195. sess.Desc("index")
  196. case "highestindex":
  197. sess.Asc("index")
  198. default:
  199. sess.Desc("created_unix")
  200. }
  201. }
  202. // CommitStatusIndex represents a table for commit status index
  203. type CommitStatusIndex struct {
  204. ID int64
  205. RepoID int64 `xorm:"unique(repo_sha)"`
  206. SHA string `xorm:"unique(repo_sha)"`
  207. MaxIndex int64 `xorm:"index"`
  208. }
  209. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
  210. func GetLatestCommitStatus(ctx context.Context, repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, int64, error) {
  211. ids := make([]int64, 0, 10)
  212. sess := db.GetEngine(ctx).Table(&CommitStatus{}).
  213. Where("repo_id = ?", repoID).And("sha = ?", sha).
  214. Select("max( id ) as id").
  215. GroupBy("context_hash").OrderBy("max( id ) desc")
  216. sess = db.SetSessionPagination(sess, &listOptions)
  217. count, err := sess.FindAndCount(&ids)
  218. if err != nil {
  219. return nil, count, err
  220. }
  221. statuses := make([]*CommitStatus, 0, len(ids))
  222. if len(ids) == 0 {
  223. return statuses, count, nil
  224. }
  225. return statuses, count, db.GetEngine(ctx).In("id", ids).Find(&statuses)
  226. }
  227. // FindRepoRecentCommitStatusContexts returns repository's recent commit status contexts
  228. func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]string, error) {
  229. start := timeutil.TimeStampNow().AddDuration(-before)
  230. ids := make([]int64, 0, 10)
  231. if err := db.GetEngine(db.DefaultContext).Table("commit_status").
  232. Where("repo_id = ?", repoID).
  233. And("updated_unix >= ?", start).
  234. Select("max( id ) as id").
  235. GroupBy("context_hash").OrderBy("max( id ) desc").
  236. Find(&ids); err != nil {
  237. return nil, err
  238. }
  239. contexts := make([]string, 0, len(ids))
  240. if len(ids) == 0 {
  241. return contexts, nil
  242. }
  243. return contexts, db.GetEngine(db.DefaultContext).Select("context").Table("commit_status").In("id", ids).Find(&contexts)
  244. }
  245. // NewCommitStatusOptions holds options for creating a CommitStatus
  246. type NewCommitStatusOptions struct {
  247. Repo *repo_model.Repository
  248. Creator *user_model.User
  249. SHA string
  250. CommitStatus *CommitStatus
  251. }
  252. // NewCommitStatus save commit statuses into database
  253. func NewCommitStatus(opts NewCommitStatusOptions) error {
  254. if opts.Repo == nil {
  255. return fmt.Errorf("NewCommitStatus[nil, %s]: no repository specified", opts.SHA)
  256. }
  257. repoPath := opts.Repo.RepoPath()
  258. if opts.Creator == nil {
  259. return fmt.Errorf("NewCommitStatus[%s, %s]: no user specified", repoPath, opts.SHA)
  260. }
  261. // Get the next Status Index
  262. idx, err := GetNextCommitStatusIndex(opts.Repo.ID, opts.SHA)
  263. if err != nil {
  264. return fmt.Errorf("generate commit status index failed: %v", err)
  265. }
  266. ctx, committer, err := db.TxContext()
  267. if err != nil {
  268. return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", opts.Repo.ID, opts.Creator.ID, opts.SHA, err)
  269. }
  270. defer committer.Close()
  271. opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description)
  272. opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context)
  273. opts.CommitStatus.TargetURL = strings.TrimSpace(opts.CommitStatus.TargetURL)
  274. opts.CommitStatus.SHA = opts.SHA
  275. opts.CommitStatus.CreatorID = opts.Creator.ID
  276. opts.CommitStatus.RepoID = opts.Repo.ID
  277. opts.CommitStatus.Index = idx
  278. log.Debug("NewCommitStatus[%s, %s]: %d", repoPath, opts.SHA, opts.CommitStatus.Index)
  279. opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context)
  280. // Insert new CommitStatus
  281. if _, err = db.GetEngine(ctx).Insert(opts.CommitStatus); err != nil {
  282. return fmt.Errorf("Insert CommitStatus[%s, %s]: %v", repoPath, opts.SHA, err)
  283. }
  284. return committer.Commit()
  285. }
  286. // SignCommitWithStatuses represents a commit with validation of signature and status state.
  287. type SignCommitWithStatuses struct {
  288. Status *CommitStatus
  289. Statuses []*CommitStatus
  290. *asymkey_model.SignCommit
  291. }
  292. // ParseCommitsWithStatus checks commits latest statuses and calculates its worst status state
  293. func ParseCommitsWithStatus(oldCommits []*asymkey_model.SignCommit, repo *repo_model.Repository) []*SignCommitWithStatuses {
  294. newCommits := make([]*SignCommitWithStatuses, 0, len(oldCommits))
  295. for _, c := range oldCommits {
  296. commit := &SignCommitWithStatuses{
  297. SignCommit: c,
  298. }
  299. statuses, _, err := GetLatestCommitStatus(db.DefaultContext, repo.ID, commit.ID.String(), db.ListOptions{})
  300. if err != nil {
  301. log.Error("GetLatestCommitStatus: %v", err)
  302. } else {
  303. commit.Statuses = statuses
  304. commit.Status = CalcCommitStatus(statuses)
  305. }
  306. newCommits = append(newCommits, commit)
  307. }
  308. return newCommits
  309. }
  310. // hashCommitStatusContext hash context
  311. func hashCommitStatusContext(context string) string {
  312. return fmt.Sprintf("%x", sha1.Sum([]byte(context)))
  313. }