ci.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package gitlab
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/porter-dev/porter/api/server/shared/commonutils"
  7. "github.com/porter-dev/porter/api/server/shared/config"
  8. "github.com/porter-dev/porter/internal/oauth"
  9. "github.com/porter-dev/porter/internal/repository"
  10. "github.com/xanzy/go-gitlab"
  11. "gopkg.in/yaml.v2"
  12. )
  13. type GitlabCI struct {
  14. ServerURL string
  15. GitRepoName string
  16. GitRepoOwner string
  17. Repo repository.Repository
  18. ProjectID uint
  19. ClusterID uint
  20. UserID uint
  21. IntegrationID uint
  22. PorterConf *config.Config
  23. ReleaseName string
  24. ReleaseNamespace string
  25. FolderPath string
  26. PorterToken string
  27. defaultGitBranch string
  28. pID string
  29. }
  30. func (g *GitlabCI) Setup() error {
  31. client, err := g.getClient()
  32. if err != nil {
  33. return err
  34. }
  35. g.pID = fmt.Sprintf("%s/%s", g.GitRepoOwner, g.GitRepoName)
  36. branches, _, err := client.Branches.ListBranches(g.pID, &gitlab.ListBranchesOptions{})
  37. if err != nil {
  38. return fmt.Errorf("error fetching list of branches: %w", err)
  39. }
  40. for _, branch := range branches {
  41. if branch.Default {
  42. g.defaultGitBranch = branch.Name
  43. break
  44. }
  45. }
  46. err = g.createGitlabSecret(client)
  47. if err != nil {
  48. return err
  49. }
  50. jobName := getGitlabStageJobName(g.ReleaseName)
  51. ciFile, resp, err := client.RepositoryFiles.GetFile(g.pID, ".gitlab-ci.yml", &gitlab.GetFileOptions{
  52. Ref: gitlab.String(g.defaultGitBranch),
  53. })
  54. if resp.StatusCode == http.StatusNotFound {
  55. // create .gitlab-ci.yml
  56. contentsMap := make(map[string]interface{})
  57. contentsMap["stages"] = []string{
  58. jobName,
  59. }
  60. contentsMap[jobName] = g.getCIJob(jobName)
  61. contentsYAML, _ := yaml.Marshal(contentsMap)
  62. _, _, err = client.RepositoryFiles.CreateFile(g.pID, ".gitlab-ci.yml", &gitlab.CreateFileOptions{
  63. Branch: gitlab.String(g.defaultGitBranch),
  64. AuthorName: gitlab.String("Porter Bot"),
  65. AuthorEmail: gitlab.String("contact@getporter.dev"),
  66. Content: gitlab.String(string(contentsYAML)),
  67. CommitMessage: gitlab.String("Create .gitlab-ci.yml file"),
  68. })
  69. if err != nil {
  70. return fmt.Errorf("error creating .gitlab-ci.yml file: %w", err)
  71. }
  72. } else if err != nil {
  73. return fmt.Errorf("error getting .gitlab-ci.yml file: %w", err)
  74. } else {
  75. // update .gitlab-ci.yml if needed
  76. ciFileContentsMap := make(map[string]interface{})
  77. err = yaml.Unmarshal([]byte(ciFile.Content), ciFileContentsMap)
  78. if err != nil {
  79. return fmt.Errorf("error unmarshalling existing .gitlab-ci.yml: %w", err)
  80. }
  81. stages, ok := ciFileContentsMap["stages"].([]string)
  82. if !ok {
  83. return fmt.Errorf("error converting stages to string slice")
  84. }
  85. stageExists := false
  86. for _, stage := range stages {
  87. if stage == jobName {
  88. stageExists = true
  89. break
  90. }
  91. }
  92. if !stageExists {
  93. stages = append(stages, jobName)
  94. ciFileContentsMap["stages"] = stages
  95. }
  96. ciFileContentsMap[jobName] = g.getCIJob(jobName)
  97. contentsYAML, _ := yaml.Marshal(ciFileContentsMap)
  98. _, _, err = client.RepositoryFiles.UpdateFile(g.pID, ".gitlab-ci.yml", &gitlab.UpdateFileOptions{
  99. Branch: gitlab.String(g.defaultGitBranch),
  100. AuthorName: gitlab.String("Porter Bot"),
  101. AuthorEmail: gitlab.String("contact@getporter.dev"),
  102. Content: gitlab.String(string(contentsYAML)),
  103. CommitMessage: gitlab.String("Update .gitlab-ci.yml file"),
  104. })
  105. if err != nil {
  106. return fmt.Errorf("error updating .gitlab-ci.yml file to add porter job: %w", err)
  107. }
  108. }
  109. return nil
  110. }
  111. func (g *GitlabCI) Cleanup() error {
  112. client, err := g.getClient()
  113. if err != nil {
  114. return err
  115. }
  116. g.pID = fmt.Sprintf("%s/%s", g.GitRepoOwner, g.GitRepoName)
  117. branches, _, err := client.Branches.ListBranches(g.pID, &gitlab.ListBranchesOptions{})
  118. if err != nil {
  119. return fmt.Errorf("error fetching list of branches: %w", err)
  120. }
  121. for _, branch := range branches {
  122. if branch.Default {
  123. g.defaultGitBranch = branch.Name
  124. break
  125. }
  126. }
  127. err = g.deleteGitlabSecret(client)
  128. if err != nil {
  129. return err
  130. }
  131. jobName := getGitlabStageJobName(g.ReleaseName)
  132. ciFile, resp, err := client.RepositoryFiles.GetFile(g.pID, ".gitlab-ci.yml", &gitlab.GetFileOptions{
  133. Ref: gitlab.String(g.defaultGitBranch),
  134. })
  135. if resp.StatusCode == http.StatusNotFound {
  136. return nil
  137. } else if err != nil {
  138. return fmt.Errorf("error getting .gitlab-ci.yml file: %w", err)
  139. }
  140. ciFileContentsMap := make(map[string]interface{})
  141. err = yaml.Unmarshal([]byte(ciFile.Content), ciFileContentsMap)
  142. if err != nil {
  143. return fmt.Errorf("error unmarshalling existing .gitlab-ci.yml: %w", err)
  144. }
  145. stages, ok := ciFileContentsMap["stages"].([]string)
  146. if !ok {
  147. return fmt.Errorf("error converting stages to string slice")
  148. }
  149. var newStages []string
  150. for _, stage := range stages {
  151. if stage != jobName {
  152. newStages = append(newStages, stage)
  153. }
  154. }
  155. ciFileContentsMap["stage"] = newStages
  156. delete(ciFileContentsMap, jobName)
  157. contentsYAML, _ := yaml.Marshal(ciFileContentsMap)
  158. _, _, err = client.RepositoryFiles.UpdateFile(g.pID, ".gitlab-ci.yml", &gitlab.UpdateFileOptions{
  159. Branch: gitlab.String(g.defaultGitBranch),
  160. AuthorName: gitlab.String("Porter Bot"),
  161. AuthorEmail: gitlab.String("contact@getporter.dev"),
  162. Content: gitlab.String(string(contentsYAML)),
  163. CommitMessage: gitlab.String("Update .gitlab-ci.yml file"),
  164. })
  165. if err != nil {
  166. return fmt.Errorf("error updating .gitlab-ci.yml file to remove porter job: %w", err)
  167. }
  168. return nil
  169. }
  170. func (g *GitlabCI) getClient() (*gitlab.Client, error) {
  171. gi, err := g.Repo.GitlabIntegration().ReadGitlabIntegration(g.ProjectID, g.IntegrationID)
  172. if err != nil {
  173. return nil, err
  174. }
  175. oauthInt, err := g.Repo.GitlabAppOAuthIntegration().ReadGitlabAppOAuthIntegration(g.UserID, g.ProjectID, g.IntegrationID)
  176. if err != nil {
  177. return nil, err
  178. }
  179. accessToken, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, commonutils.GetGitlabOAuthConf(g.PorterConf, gi),
  180. oauth.MakeUpdateGitlabAppOAuthIntegrationFunction(oauthInt, g.Repo))
  181. if err != nil {
  182. return nil, err
  183. }
  184. client, err := gitlab.NewOAuthClient(accessToken, gitlab.WithBaseURL(gi.InstanceURL))
  185. if err != nil {
  186. return nil, err
  187. }
  188. return client, nil
  189. }
  190. func (g *GitlabCI) getCIJob(jobName string) map[string]interface{} {
  191. return map[string]interface{}{
  192. "image": "public.ecr.aws/o1j4x7p4/porter-cli:latest",
  193. "stage": jobName,
  194. "timeout": "20 minutes",
  195. "variables": map[string]string{
  196. "GIT_STRATEGY": "clone",
  197. },
  198. "script": []string{
  199. fmt.Sprintf("export PORTER_HOST=\"%s\"", g.ServerURL),
  200. fmt.Sprintf("export PORTER_PROJECT=\"%d\"", g.ProjectID),
  201. fmt.Sprintf("export PORTER_CLUSTER=\"%d\"", g.ClusterID),
  202. fmt.Sprintf("export PORTER_TOKEN=\"$%s\"", g.getPorterTokenSecretName()),
  203. "export PORTER_TAG=\"$(echo $CI_COMMIT_SHA | cut -c1-7)\"",
  204. fmt.Sprintf("porter update --app \"%s\" --tag \"$PORTER_TAG\" --namespace \"%s\" --path \"%s\" --stream",
  205. g.ReleaseName, g.ReleaseNamespace, g.FolderPath),
  206. },
  207. }
  208. }
  209. func (g *GitlabCI) createGitlabSecret(client *gitlab.Client) error {
  210. _, _, err := client.ProjectVariables.CreateVariable(g.pID, &gitlab.CreateProjectVariableOptions{
  211. Key: gitlab.String(g.getPorterTokenSecretName()),
  212. Value: gitlab.String(g.PorterToken),
  213. Masked: gitlab.Bool(true),
  214. })
  215. if err != nil {
  216. return fmt.Errorf("error creating porter token variable: %w", err)
  217. }
  218. return nil
  219. }
  220. func (g *GitlabCI) deleteGitlabSecret(client *gitlab.Client) error {
  221. _, err := client.ProjectVariables.RemoveVariable(g.pID, g.getPorterTokenSecretName(), &gitlab.RemoveProjectVariableOptions{})
  222. if err != nil {
  223. return fmt.Errorf("error removing porter token variable: %w", err)
  224. }
  225. return nil
  226. }
  227. func (g *GitlabCI) getPorterTokenSecretName() string {
  228. return fmt.Sprintf("PORTER_TOKEN_%d", g.ProjectID)
  229. }
  230. func getGitlabStageJobName(releaseName string) string {
  231. return fmt.Sprintf("porter-%s", strings.ToLower(strings.ReplaceAll(releaseName, "_", "-")))
  232. }