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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. "net/url"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/models/db"
  12. user_model "code.gitea.io/gitea/models/user"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. api "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "xorm.io/xorm"
  18. )
  19. // CommitStatus holds a single Status of a single Commit
  20. type CommitStatus struct {
  21. ID int64 `xorm:"pk autoincr"`
  22. Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  23. RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  24. Repo *Repository `xorm:"-"`
  25. State api.CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
  26. SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
  27. TargetURL string `xorm:"TEXT"`
  28. Description string `xorm:"TEXT"`
  29. ContextHash string `xorm:"char(40) index"`
  30. Context string `xorm:"TEXT"`
  31. Creator *user_model.User `xorm:"-"`
  32. CreatorID int64
  33. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  34. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  35. }
  36. func init() {
  37. db.RegisterModel(new(CommitStatus))
  38. db.RegisterModel(new(CommitStatusIndex))
  39. }
  40. // upsertCommitStatusIndex the function will not return until it acquires the lock or receives an error.
  41. func upsertCommitStatusIndex(e db.Engine, repoID int64, sha string) (err error) {
  42. // An atomic UPSERT operation (INSERT/UPDATE) is the only operation
  43. // that ensures that the key is actually locked.
  44. switch {
  45. case setting.Database.UseSQLite3 || setting.Database.UsePostgreSQL:
  46. _, err = e.Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
  47. "VALUES (?,?,1) ON CONFLICT (repo_id,sha) DO UPDATE SET max_index = `commit_status_index`.max_index+1",
  48. repoID, sha)
  49. case setting.Database.UseMySQL:
  50. _, err = e.Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
  51. "VALUES (?,?,1) ON DUPLICATE KEY UPDATE max_index = max_index+1",
  52. repoID, sha)
  53. case setting.Database.UseMSSQL:
  54. // https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/
  55. _, err = e.Exec("MERGE `commit_status_index` WITH (HOLDLOCK) as target "+
  56. "USING (SELECT ? AS repo_id, ? AS sha) AS src "+
  57. "ON src.repo_id = target.repo_id AND src.sha = target.sha "+
  58. "WHEN MATCHED THEN UPDATE SET target.max_index = target.max_index+1 "+
  59. "WHEN NOT MATCHED THEN INSERT (repo_id, sha, max_index) "+
  60. "VALUES (src.repo_id, src.sha, 1);",
  61. repoID, sha)
  62. default:
  63. return fmt.Errorf("database type not supported")
  64. }
  65. return
  66. }
  67. // GetNextCommitStatusIndex retried 3 times to generate a resource index
  68. func GetNextCommitStatusIndex(repoID int64, sha string) (int64, error) {
  69. for i := 0; i < db.MaxDupIndexAttempts; i++ {
  70. idx, err := getNextCommitStatusIndex(repoID, sha)
  71. if err == db.ErrResouceOutdated {
  72. continue
  73. }
  74. if err != nil {
  75. return 0, err
  76. }
  77. return idx, nil
  78. }
  79. return 0, db.ErrGetResourceIndexFailed
  80. }
  81. // getNextCommitStatusIndex return the next index
  82. func getNextCommitStatusIndex(repoID int64, sha string) (int64, error) {
  83. ctx, commiter, err := db.TxContext()
  84. if err != nil {
  85. return 0, err
  86. }
  87. defer commiter.Close()
  88. var preIdx int64
  89. _, err = ctx.Engine().SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ?", repoID, sha).Get(&preIdx)
  90. if err != nil {
  91. return 0, err
  92. }
  93. if err := upsertCommitStatusIndex(ctx.Engine(), repoID, sha); err != nil {
  94. return 0, err
  95. }
  96. var curIdx int64
  97. 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)
  98. if err != nil {
  99. return 0, err
  100. }
  101. if !has {
  102. return 0, db.ErrResouceOutdated
  103. }
  104. if err := commiter.Commit(); err != nil {
  105. return 0, err
  106. }
  107. return curIdx, nil
  108. }
  109. func (status *CommitStatus) loadAttributes(e db.Engine) (err error) {
  110. if status.Repo == nil {
  111. status.Repo, err = getRepositoryByID(e, status.RepoID)
  112. if err != nil {
  113. return fmt.Errorf("getRepositoryByID [%d]: %v", status.RepoID, err)
  114. }
  115. }
  116. if status.Creator == nil && status.CreatorID > 0 {
  117. status.Creator, err = user_model.GetUserByIDEngine(e, status.CreatorID)
  118. if err != nil {
  119. return fmt.Errorf("getUserByID [%d]: %v", status.CreatorID, err)
  120. }
  121. }
  122. return nil
  123. }
  124. // APIURL returns the absolute APIURL to this commit-status.
  125. func (status *CommitStatus) APIURL() string {
  126. _ = status.loadAttributes(db.GetEngine(db.DefaultContext))
  127. return status.Repo.APIURL() + "/statuses/" + url.PathEscape(status.SHA)
  128. }
  129. // CalcCommitStatus returns commit status state via some status, the commit statues should order by id desc
  130. func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus {
  131. var lastStatus *CommitStatus
  132. var state api.CommitStatusState
  133. for _, status := range statuses {
  134. if status.State.NoBetterThan(state) {
  135. state = status.State
  136. lastStatus = status
  137. }
  138. }
  139. if lastStatus == nil {
  140. if len(statuses) > 0 {
  141. lastStatus = statuses[0]
  142. } else {
  143. lastStatus = &CommitStatus{}
  144. }
  145. }
  146. return lastStatus
  147. }
  148. // CommitStatusOptions holds the options for query commit statuses
  149. type CommitStatusOptions struct {
  150. db.ListOptions
  151. State string
  152. SortType string
  153. }
  154. // GetCommitStatuses returns all statuses for a given commit.
  155. func GetCommitStatuses(repo *Repository, sha string, opts *CommitStatusOptions) ([]*CommitStatus, int64, error) {
  156. if opts.Page <= 0 {
  157. opts.Page = 1
  158. }
  159. if opts.PageSize <= 0 {
  160. opts.Page = ItemsPerPage
  161. }
  162. countSession := listCommitStatusesStatement(repo, sha, opts)
  163. countSession = db.SetSessionPagination(countSession, opts)
  164. maxResults, err := countSession.Count(new(CommitStatus))
  165. if err != nil {
  166. log.Error("Count PRs: %v", err)
  167. return nil, maxResults, err
  168. }
  169. statuses := make([]*CommitStatus, 0, opts.PageSize)
  170. findSession := listCommitStatusesStatement(repo, sha, opts)
  171. findSession = db.SetSessionPagination(findSession, opts)
  172. sortCommitStatusesSession(findSession, opts.SortType)
  173. return statuses, maxResults, findSession.Find(&statuses)
  174. }
  175. func listCommitStatusesStatement(repo *Repository, sha string, opts *CommitStatusOptions) *xorm.Session {
  176. sess := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).And("sha = ?", sha)
  177. switch opts.State {
  178. case "pending", "success", "error", "failure", "warning":
  179. sess.And("state = ?", opts.State)
  180. }
  181. return sess
  182. }
  183. func sortCommitStatusesSession(sess *xorm.Session, sortType string) {
  184. switch sortType {
  185. case "oldest":
  186. sess.Asc("created_unix")
  187. case "recentupdate":
  188. sess.Desc("updated_unix")
  189. case "leastupdate":
  190. sess.Asc("updated_unix")
  191. case "leastindex":
  192. sess.Desc("index")
  193. case "highestindex":
  194. sess.Asc("index")
  195. default:
  196. sess.Desc("created_unix")
  197. }
  198. }
  199. // CommitStatusIndex represents a table for commit status index
  200. type CommitStatusIndex struct {
  201. ID int64
  202. RepoID int64 `xorm:"unique(repo_sha)"`
  203. SHA string `xorm:"unique(repo_sha)"`
  204. MaxIndex int64 `xorm:"index"`
  205. }
  206. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
  207. func GetLatestCommitStatus(repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, error) {
  208. return getLatestCommitStatus(db.GetEngine(db.DefaultContext), repoID, sha, listOptions)
  209. }
  210. func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, error) {
  211. ids := make([]int64, 0, 10)
  212. sess := e.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. err := sess.Find(&ids)
  218. if err != nil {
  219. return nil, err
  220. }
  221. statuses := make([]*CommitStatus, 0, len(ids))
  222. if len(ids) == 0 {
  223. return statuses, nil
  224. }
  225. return statuses, e.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 *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. *SignCommit
  291. }
  292. // ParseCommitsWithStatus checks commits latest statuses and calculates its worst status state
  293. func ParseCommitsWithStatus(oldCommits []*SignCommit, repo *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(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. }