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.

delete.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package repository
  4. import (
  5. "context"
  6. "fmt"
  7. "code.gitea.io/gitea/models"
  8. actions_model "code.gitea.io/gitea/models/actions"
  9. activities_model "code.gitea.io/gitea/models/activities"
  10. admin_model "code.gitea.io/gitea/models/admin"
  11. asymkey_model "code.gitea.io/gitea/models/asymkey"
  12. "code.gitea.io/gitea/models/db"
  13. git_model "code.gitea.io/gitea/models/git"
  14. issues_model "code.gitea.io/gitea/models/issues"
  15. "code.gitea.io/gitea/models/organization"
  16. access_model "code.gitea.io/gitea/models/perm/access"
  17. project_model "code.gitea.io/gitea/models/project"
  18. repo_model "code.gitea.io/gitea/models/repo"
  19. secret_model "code.gitea.io/gitea/models/secret"
  20. system_model "code.gitea.io/gitea/models/system"
  21. user_model "code.gitea.io/gitea/models/user"
  22. "code.gitea.io/gitea/models/webhook"
  23. actions_module "code.gitea.io/gitea/modules/actions"
  24. "code.gitea.io/gitea/modules/lfs"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/storage"
  27. asymkey_service "code.gitea.io/gitea/services/asymkey"
  28. "xorm.io/builder"
  29. )
  30. // DeleteRepository deletes a repository for a user or organization.
  31. // make sure if you call this func to close open sessions (sqlite will otherwise get a deadlock)
  32. func DeleteRepositoryDirectly(ctx context.Context, doer *user_model.User, repoID int64, ignoreOrgTeams ...bool) error {
  33. ctx, committer, err := db.TxContext(ctx)
  34. if err != nil {
  35. return err
  36. }
  37. defer committer.Close()
  38. sess := db.GetEngine(ctx)
  39. repo := &repo_model.Repository{}
  40. has, err := sess.ID(repoID).Get(repo)
  41. if err != nil {
  42. return err
  43. } else if !has {
  44. return repo_model.ErrRepoNotExist{
  45. ID: repoID,
  46. OwnerName: "",
  47. Name: "",
  48. }
  49. }
  50. // Query the action tasks of this repo, they will be needed after they have been deleted to remove the logs
  51. tasks, err := db.Find[actions_model.ActionTask](ctx, actions_model.FindTaskOptions{RepoID: repoID})
  52. if err != nil {
  53. return fmt.Errorf("find actions tasks of repo %v: %w", repoID, err)
  54. }
  55. // Query the artifacts of this repo, they will be needed after they have been deleted to remove artifacts files in ObjectStorage
  56. artifacts, err := db.Find[actions_model.ActionArtifact](ctx, actions_model.FindArtifactsOptions{RepoID: repoID})
  57. if err != nil {
  58. return fmt.Errorf("list actions artifacts of repo %v: %w", repoID, err)
  59. }
  60. // In case owner is a organization, we have to change repo specific teams
  61. // if ignoreOrgTeams is not true
  62. var org *user_model.User
  63. if len(ignoreOrgTeams) == 0 || !ignoreOrgTeams[0] {
  64. if org, err = user_model.GetUserByID(ctx, repo.OwnerID); err != nil {
  65. return err
  66. }
  67. }
  68. // Delete Deploy Keys
  69. deployKeys, err := db.Find[asymkey_model.DeployKey](ctx, asymkey_model.ListDeployKeysOptions{RepoID: repoID})
  70. if err != nil {
  71. return fmt.Errorf("listDeployKeys: %w", err)
  72. }
  73. needRewriteKeysFile := len(deployKeys) > 0
  74. for _, dKey := range deployKeys {
  75. if err := models.DeleteDeployKey(ctx, doer, dKey.ID); err != nil {
  76. return fmt.Errorf("deleteDeployKeys: %w", err)
  77. }
  78. }
  79. if cnt, err := sess.ID(repoID).Delete(&repo_model.Repository{}); err != nil {
  80. return err
  81. } else if cnt != 1 {
  82. return repo_model.ErrRepoNotExist{
  83. ID: repoID,
  84. OwnerName: "",
  85. Name: "",
  86. }
  87. }
  88. if org != nil && org.IsOrganization() {
  89. teams, err := organization.FindOrgTeams(ctx, org.ID)
  90. if err != nil {
  91. return err
  92. }
  93. for _, t := range teams {
  94. if !organization.HasTeamRepo(ctx, t.OrgID, t.ID, repoID) {
  95. continue
  96. } else if err = removeRepositoryFromTeam(ctx, t, repo, false); err != nil {
  97. return err
  98. }
  99. }
  100. }
  101. attachments := make([]*repo_model.Attachment, 0, 20)
  102. if err = sess.Join("INNER", "`release`", "`release`.id = `attachment`.release_id").
  103. Where("`release`.repo_id = ?", repoID).
  104. Find(&attachments); err != nil {
  105. return err
  106. }
  107. releaseAttachments := make([]string, 0, len(attachments))
  108. for i := 0; i < len(attachments); i++ {
  109. releaseAttachments = append(releaseAttachments, attachments[i].RelativePath())
  110. }
  111. if _, err := db.Exec(ctx, "UPDATE `user` SET num_stars=num_stars-1 WHERE id IN (SELECT `uid` FROM `star` WHERE repo_id = ?)", repo.ID); err != nil {
  112. return err
  113. }
  114. if _, err := db.GetEngine(ctx).In("hook_id", builder.Select("id").From("webhook").Where(builder.Eq{"webhook.repo_id": repo.ID})).
  115. Delete(&webhook.HookTask{}); err != nil {
  116. return err
  117. }
  118. if err := db.DeleteBeans(ctx,
  119. &access_model.Access{RepoID: repo.ID},
  120. &activities_model.Action{RepoID: repo.ID},
  121. &repo_model.Collaboration{RepoID: repoID},
  122. &issues_model.Comment{RefRepoID: repoID},
  123. &git_model.CommitStatus{RepoID: repoID},
  124. &git_model.Branch{RepoID: repoID},
  125. &git_model.LFSLock{RepoID: repoID},
  126. &repo_model.LanguageStat{RepoID: repoID},
  127. &issues_model.Milestone{RepoID: repoID},
  128. &repo_model.Mirror{RepoID: repoID},
  129. &activities_model.Notification{RepoID: repoID},
  130. &git_model.ProtectedBranch{RepoID: repoID},
  131. &git_model.ProtectedTag{RepoID: repoID},
  132. &repo_model.PushMirror{RepoID: repoID},
  133. &repo_model.Release{RepoID: repoID},
  134. &repo_model.RepoIndexerStatus{RepoID: repoID},
  135. &repo_model.Redirect{RedirectRepoID: repoID},
  136. &repo_model.RepoUnit{RepoID: repoID},
  137. &repo_model.Star{RepoID: repoID},
  138. &admin_model.Task{RepoID: repoID},
  139. &repo_model.Watch{RepoID: repoID},
  140. &webhook.Webhook{RepoID: repoID},
  141. &secret_model.Secret{RepoID: repoID},
  142. &actions_model.ActionTaskStep{RepoID: repoID},
  143. &actions_model.ActionTask{RepoID: repoID},
  144. &actions_model.ActionRunJob{RepoID: repoID},
  145. &actions_model.ActionRun{RepoID: repoID},
  146. &actions_model.ActionRunner{RepoID: repoID},
  147. &actions_model.ActionScheduleSpec{RepoID: repoID},
  148. &actions_model.ActionSchedule{RepoID: repoID},
  149. &actions_model.ActionArtifact{RepoID: repoID},
  150. ); err != nil {
  151. return fmt.Errorf("deleteBeans: %w", err)
  152. }
  153. // Delete Labels and related objects
  154. if err := issues_model.DeleteLabelsByRepoID(ctx, repoID); err != nil {
  155. return err
  156. }
  157. // Delete Pulls and related objects
  158. if err := issues_model.DeletePullsByBaseRepoID(ctx, repoID); err != nil {
  159. return err
  160. }
  161. // Delete Issues and related objects
  162. var attachmentPaths []string
  163. if attachmentPaths, err = issues_model.DeleteIssuesByRepoID(ctx, repoID); err != nil {
  164. return err
  165. }
  166. // Delete issue index
  167. if err := db.DeleteResourceIndex(ctx, "issue_index", repoID); err != nil {
  168. return err
  169. }
  170. if repo.IsFork {
  171. if _, err := db.Exec(ctx, "UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  172. return fmt.Errorf("decrease fork count: %w", err)
  173. }
  174. }
  175. if _, err := db.Exec(ctx, "UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", repo.OwnerID); err != nil {
  176. return err
  177. }
  178. if len(repo.Topics) > 0 {
  179. if err := repo_model.RemoveTopicsFromRepo(ctx, repo.ID); err != nil {
  180. return err
  181. }
  182. }
  183. if err := project_model.DeleteProjectByRepoID(ctx, repoID); err != nil {
  184. return fmt.Errorf("unable to delete projects for repo[%d]: %w", repoID, err)
  185. }
  186. // Remove LFS objects
  187. var lfsObjects []*git_model.LFSMetaObject
  188. if err = sess.Where("repository_id=?", repoID).Find(&lfsObjects); err != nil {
  189. return err
  190. }
  191. lfsPaths := make([]string, 0, len(lfsObjects))
  192. for _, v := range lfsObjects {
  193. count, err := db.CountByBean(ctx, &git_model.LFSMetaObject{Pointer: lfs.Pointer{Oid: v.Oid}})
  194. if err != nil {
  195. return err
  196. }
  197. if count > 1 {
  198. continue
  199. }
  200. lfsPaths = append(lfsPaths, v.RelativePath())
  201. }
  202. if _, err := db.DeleteByBean(ctx, &git_model.LFSMetaObject{RepositoryID: repoID}); err != nil {
  203. return err
  204. }
  205. // Remove archives
  206. var archives []*repo_model.RepoArchiver
  207. if err = sess.Where("repo_id=?", repoID).Find(&archives); err != nil {
  208. return err
  209. }
  210. archivePaths := make([]string, 0, len(archives))
  211. for _, v := range archives {
  212. archivePaths = append(archivePaths, v.RelativePath())
  213. }
  214. if _, err := db.DeleteByBean(ctx, &repo_model.RepoArchiver{RepoID: repoID}); err != nil {
  215. return err
  216. }
  217. if repo.NumForks > 0 {
  218. if _, err = sess.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  219. log.Error("reset 'fork_id' and 'is_fork': %v", err)
  220. }
  221. }
  222. // Get all attachments with both issue_id and release_id are zero
  223. var newAttachments []*repo_model.Attachment
  224. if err := sess.Where(builder.Eq{
  225. "repo_id": repo.ID,
  226. "issue_id": 0,
  227. "release_id": 0,
  228. }).Find(&newAttachments); err != nil {
  229. return err
  230. }
  231. newAttachmentPaths := make([]string, 0, len(newAttachments))
  232. for _, attach := range newAttachments {
  233. newAttachmentPaths = append(newAttachmentPaths, attach.RelativePath())
  234. }
  235. if _, err := sess.Where("repo_id=?", repo.ID).Delete(new(repo_model.Attachment)); err != nil {
  236. return err
  237. }
  238. if err = committer.Commit(); err != nil {
  239. return err
  240. }
  241. committer.Close()
  242. if needRewriteKeysFile {
  243. if err := asymkey_service.RewriteAllPublicKeys(ctx); err != nil {
  244. log.Error("RewriteAllPublicKeys failed: %v", err)
  245. }
  246. }
  247. // We should always delete the files after the database transaction succeed. If
  248. // we delete the file but the database rollback, the repository will be broken.
  249. // Remove repository files.
  250. repoPath := repo.RepoPath()
  251. system_model.RemoveAllWithNotice(ctx, "Delete repository files", repoPath)
  252. // Remove wiki files
  253. if repo.HasWiki() {
  254. system_model.RemoveAllWithNotice(ctx, "Delete repository wiki", repo.WikiPath())
  255. }
  256. // Remove archives
  257. for _, archive := range archivePaths {
  258. system_model.RemoveStorageWithNotice(ctx, storage.RepoArchives, "Delete repo archive file", archive)
  259. }
  260. // Remove lfs objects
  261. for _, lfsObj := range lfsPaths {
  262. system_model.RemoveStorageWithNotice(ctx, storage.LFS, "Delete orphaned LFS file", lfsObj)
  263. }
  264. // Remove issue attachment files.
  265. for _, attachment := range attachmentPaths {
  266. system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete issue attachment", attachment)
  267. }
  268. // Remove release attachment files.
  269. for _, releaseAttachment := range releaseAttachments {
  270. system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete release attachment", releaseAttachment)
  271. }
  272. // Remove attachment with no issue_id and release_id.
  273. for _, newAttachment := range newAttachmentPaths {
  274. system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete issue attachment", newAttachment)
  275. }
  276. if len(repo.Avatar) > 0 {
  277. if err := storage.RepoAvatars.Delete(repo.CustomAvatarRelativePath()); err != nil {
  278. return fmt.Errorf("Failed to remove %s: %w", repo.Avatar, err)
  279. }
  280. }
  281. // Finally, delete action logs after the actions have already been deleted to avoid new log files
  282. for _, task := range tasks {
  283. err := actions_module.RemoveLogs(ctx, task.LogInStorage, task.LogFilename)
  284. if err != nil {
  285. log.Error("remove log file %q: %v", task.LogFilename, err)
  286. // go on
  287. }
  288. }
  289. // delete actions artifacts in ObjectStorage after the repo have already been deleted
  290. for _, art := range artifacts {
  291. if err := storage.ActionsArtifacts.Delete(art.StoragePath); err != nil {
  292. log.Error("remove artifact file %q: %v", art.StoragePath, err)
  293. // go on
  294. }
  295. }
  296. return nil
  297. }
  298. // removeRepositoryFromTeam removes a repository from a team and recalculates access
  299. // Note: Repository shall not be removed from team if it includes all repositories (unless the repository is deleted)
  300. func removeRepositoryFromTeam(ctx context.Context, t *organization.Team, repo *repo_model.Repository, recalculate bool) (err error) {
  301. e := db.GetEngine(ctx)
  302. if err = organization.RemoveTeamRepo(ctx, t.ID, repo.ID); err != nil {
  303. return err
  304. }
  305. t.NumRepos--
  306. if _, err = e.ID(t.ID).Cols("num_repos").Update(t); err != nil {
  307. return err
  308. }
  309. // Don't need to recalculate when delete a repository from organization.
  310. if recalculate {
  311. if err = access_model.RecalculateTeamAccesses(ctx, repo, t.ID); err != nil {
  312. return err
  313. }
  314. }
  315. teamMembers, err := organization.GetTeamMembers(ctx, &organization.SearchMembersOptions{
  316. TeamID: t.ID,
  317. })
  318. if err != nil {
  319. return fmt.Errorf("GetTeamMembers: %w", err)
  320. }
  321. for _, member := range teamMembers {
  322. has, err := access_model.HasAccess(ctx, member.ID, repo)
  323. if err != nil {
  324. return err
  325. } else if has {
  326. continue
  327. }
  328. if err = repo_model.WatchRepo(ctx, member, repo, false); err != nil {
  329. return err
  330. }
  331. // Remove all IssueWatches a user has subscribed to in the repositories
  332. if err := issues_model.RemoveIssueWatchersByRepoID(ctx, member.ID, repo.ID); err != nil {
  333. return err
  334. }
  335. }
  336. return nil
  337. }
  338. // HasRepository returns true if given repository belong to team.
  339. func HasRepository(ctx context.Context, t *organization.Team, repoID int64) bool {
  340. return organization.HasTeamRepo(ctx, t.OrgID, t.ID, repoID)
  341. }
  342. // RemoveRepositoryFromTeam removes repository from team of organization.
  343. // If the team shall include all repositories the request is ignored.
  344. func RemoveRepositoryFromTeam(ctx context.Context, t *organization.Team, repoID int64) error {
  345. if !HasRepository(ctx, t, repoID) {
  346. return nil
  347. }
  348. if t.IncludesAllRepositories {
  349. return nil
  350. }
  351. repo, err := repo_model.GetRepositoryByID(ctx, repoID)
  352. if err != nil {
  353. return err
  354. }
  355. ctx, committer, err := db.TxContext(ctx)
  356. if err != nil {
  357. return err
  358. }
  359. defer committer.Close()
  360. if err = removeRepositoryFromTeam(ctx, t, repo, true); err != nil {
  361. return err
  362. }
  363. return committer.Commit()
  364. }
  365. // DeleteOwnerRepositoriesDirectly calls DeleteRepositoryDirectly for all repos of the given owner
  366. func DeleteOwnerRepositoriesDirectly(ctx context.Context, owner *user_model.User) error {
  367. for {
  368. repos, _, err := repo_model.GetUserRepositories(ctx, &repo_model.SearchRepoOptions{
  369. ListOptions: db.ListOptions{
  370. PageSize: repo_model.RepositoryListDefaultPageSize,
  371. Page: 1,
  372. },
  373. Private: true,
  374. OwnerID: owner.ID,
  375. Actor: owner,
  376. })
  377. if err != nil {
  378. return fmt.Errorf("GetUserRepositories: %w", err)
  379. }
  380. if len(repos) == 0 {
  381. break
  382. }
  383. for _, repo := range repos {
  384. if err := DeleteRepositoryDirectly(ctx, owner, repo.ID); err != nil {
  385. return fmt.Errorf("unable to delete repository %s for %s[%d]. Error: %w", repo.Name, owner.Name, owner.ID, err)
  386. }
  387. }
  388. }
  389. return nil
  390. }