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