global_stream.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. package provisioner
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "regexp"
  8. "strings"
  9. "github.com/aws/aws-sdk-go/service/ecr"
  10. "github.com/porter-dev/porter/internal/repository"
  11. redis "github.com/go-redis/redis/v8"
  12. "github.com/porter-dev/porter/internal/models"
  13. )
  14. // GlobalStreamName is the name of the Redis stream for global operations
  15. const GlobalStreamName = "global"
  16. // GlobalStreamGroupName is the name of the Redis consumer group that this server
  17. // is a part of
  18. const GlobalStreamGroupName = "portersvr"
  19. // InitGlobalStream initializes the global stream if it does not exist, and the
  20. // global consumer group if it does not exist
  21. func InitGlobalStream(client *redis.Client) error {
  22. // determine if the stream exists
  23. x, err := client.Exists(
  24. context.Background(),
  25. GlobalStreamName,
  26. ).Result()
  27. // if it does not exist, create group and stream
  28. if x == 0 {
  29. _, err := client.XGroupCreateMkStream(
  30. context.Background(),
  31. GlobalStreamName,
  32. GlobalStreamGroupName,
  33. ">",
  34. ).Result()
  35. return err
  36. }
  37. // otherwise, check if the group exists
  38. xInfoGroups, err := client.XInfoGroups(
  39. context.Background(),
  40. GlobalStreamName,
  41. ).Result()
  42. // if error is not NOGROUP error, return
  43. if err != nil && !strings.Contains(err.Error(), "NOGROUP") {
  44. return err
  45. }
  46. for _, group := range xInfoGroups {
  47. // if the group exists, return with no error
  48. if group.Name == GlobalStreamGroupName {
  49. return nil
  50. }
  51. }
  52. // if the group does not exist, create it
  53. _, err = client.XGroupCreate(
  54. context.Background(),
  55. GlobalStreamName,
  56. GlobalStreamGroupName,
  57. "$",
  58. ).Result()
  59. return err
  60. }
  61. // ResourceCRUDHandler is a handler for updates to an infra resource
  62. type ResourceCRUDHandler interface {
  63. OnCreate(id uint) error
  64. }
  65. // GlobalStreamListener performs an XREADGROUP operation on a given stream and
  66. // updates models in the database as necessary
  67. func GlobalStreamListener(
  68. client *redis.Client,
  69. repo repository.Repository,
  70. errorChan chan error,
  71. ) {
  72. for {
  73. xstreams, err := client.XReadGroup(
  74. context.Background(),
  75. &redis.XReadGroupArgs{
  76. Group: GlobalStreamGroupName,
  77. Consumer: "portersvr-0", // just static consumer for now
  78. Streams: []string{GlobalStreamName, ">"},
  79. Block: 0,
  80. },
  81. ).Result()
  82. if err != nil {
  83. errorChan <- err
  84. return
  85. }
  86. // parse messages from the global stream
  87. for _, msg := range xstreams[0].Messages {
  88. // parse the id to identify the infra
  89. kind, projID, infraID, err := models.ParseUniqueName(fmt.Sprintf("%v", msg.Values["id"]))
  90. if fmt.Sprintf("%v", msg.Values["status"]) == "created" {
  91. infra, err := repo.Infra.ReadInfra(infraID)
  92. if err != nil {
  93. continue
  94. }
  95. infra.Status = models.StatusCreated
  96. infra, err = repo.Infra.UpdateInfra(infra)
  97. if err != nil {
  98. continue
  99. }
  100. // create ECR/EKS
  101. if kind == string(models.InfraECR) {
  102. reg := &models.Registry{
  103. ProjectID: projID,
  104. AWSIntegrationID: infra.AWSIntegrationID,
  105. InfraID: infra.ID,
  106. }
  107. // parse raw data into ECR type
  108. dataString, ok := msg.Values["data"].(string)
  109. if ok {
  110. json.Unmarshal([]byte(dataString), reg)
  111. }
  112. awsInt, err := repo.AWSIntegration.ReadAWSIntegration(reg.AWSIntegrationID)
  113. if err != nil {
  114. continue
  115. }
  116. sess, err := awsInt.GetSession()
  117. if err != nil {
  118. continue
  119. }
  120. ecrSvc := ecr.New(sess)
  121. output, err := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{})
  122. if err != nil {
  123. continue
  124. }
  125. reg.URL = *output.AuthorizationData[0].ProxyEndpoint
  126. reg, err = repo.Registry.CreateRegistry(reg)
  127. if err != nil {
  128. continue
  129. }
  130. } else if kind == string(models.InfraEKS) {
  131. cluster := &models.Cluster{
  132. AuthMechanism: models.AWS,
  133. ProjectID: projID,
  134. AWSIntegrationID: infra.AWSIntegrationID,
  135. InfraID: infra.ID,
  136. }
  137. // parse raw data into ECR type
  138. dataString, ok := msg.Values["data"].(string)
  139. if ok {
  140. json.Unmarshal([]byte(dataString), cluster)
  141. }
  142. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  143. // if it matches the base64 regex, decode it
  144. caData := string(cluster.CertificateAuthorityData)
  145. if re.MatchString(caData) {
  146. decoded, err := base64.StdEncoding.DecodeString(caData)
  147. if err != nil {
  148. continue
  149. }
  150. cluster.CertificateAuthorityData = []byte(decoded)
  151. }
  152. cluster, err := repo.Cluster.CreateCluster(cluster)
  153. if err != nil {
  154. continue
  155. }
  156. } else if kind == string(models.InfraGCR) {
  157. reg := &models.Registry{
  158. ProjectID: projID,
  159. GCPIntegrationID: infra.GCPIntegrationID,
  160. InfraID: infra.ID,
  161. Name: "gcr-registry",
  162. }
  163. // parse raw data into ECR type
  164. dataString, ok := msg.Values["data"].(string)
  165. if ok {
  166. json.Unmarshal([]byte(dataString), reg)
  167. }
  168. reg, err = repo.Registry.CreateRegistry(reg)
  169. if err != nil {
  170. continue
  171. }
  172. } else if kind == string(models.InfraGKE) {
  173. cluster := &models.Cluster{
  174. AuthMechanism: models.GCP,
  175. ProjectID: projID,
  176. GCPIntegrationID: infra.GCPIntegrationID,
  177. InfraID: infra.ID,
  178. }
  179. // parse raw data into GKE type
  180. dataString, ok := msg.Values["data"].(string)
  181. if ok {
  182. json.Unmarshal([]byte(dataString), cluster)
  183. }
  184. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  185. // if it matches the base64 regex, decode it
  186. caData := string(cluster.CertificateAuthorityData)
  187. if re.MatchString(caData) {
  188. decoded, err := base64.StdEncoding.DecodeString(caData)
  189. if err != nil {
  190. continue
  191. }
  192. cluster.CertificateAuthorityData = []byte(decoded)
  193. }
  194. cluster, err := repo.Cluster.CreateCluster(cluster)
  195. if err != nil {
  196. continue
  197. }
  198. } else if kind == string(models.InfraDOCR) {
  199. reg := &models.Registry{
  200. ProjectID: projID,
  201. DOIntegrationID: infra.DOIntegrationID,
  202. InfraID: infra.ID,
  203. }
  204. // parse raw data into DOCR type
  205. dataString, ok := msg.Values["data"].(string)
  206. if ok {
  207. json.Unmarshal([]byte(dataString), reg)
  208. }
  209. reg, err = repo.Registry.CreateRegistry(reg)
  210. if err != nil {
  211. continue
  212. }
  213. } else if kind == string(models.InfraDOKS) {
  214. cluster := &models.Cluster{
  215. AuthMechanism: models.DO,
  216. ProjectID: projID,
  217. DOIntegrationID: infra.DOIntegrationID,
  218. InfraID: infra.ID,
  219. }
  220. // parse raw data into GKE type
  221. dataString, ok := msg.Values["data"].(string)
  222. if ok {
  223. json.Unmarshal([]byte(dataString), cluster)
  224. }
  225. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  226. // if it matches the base64 regex, decode it
  227. caData := string(cluster.CertificateAuthorityData)
  228. if re.MatchString(caData) {
  229. decoded, err := base64.StdEncoding.DecodeString(caData)
  230. if err != nil {
  231. continue
  232. }
  233. cluster.CertificateAuthorityData = []byte(decoded)
  234. }
  235. cluster, err := repo.Cluster.CreateCluster(cluster)
  236. if err != nil {
  237. continue
  238. }
  239. }
  240. } else if fmt.Sprintf("%v", msg.Values["status"]) == "error" {
  241. infra, err := repo.Infra.ReadInfra(infraID)
  242. if err != nil {
  243. continue
  244. }
  245. infra.Status = models.StatusError
  246. infra, err = repo.Infra.UpdateInfra(infra)
  247. if err != nil {
  248. continue
  249. }
  250. } else if fmt.Sprintf("%v", msg.Values["status"]) == "destroyed" {
  251. infra, err := repo.Infra.ReadInfra(infraID)
  252. if err != nil {
  253. continue
  254. }
  255. infra.Status = models.StatusDestroyed
  256. infra, err = repo.Infra.UpdateInfra(infra)
  257. if err != nil {
  258. continue
  259. }
  260. }
  261. // acknowledge the message as read
  262. _, err = client.XAck(
  263. context.Background(),
  264. GlobalStreamName,
  265. GlobalStreamGroupName,
  266. msg.ID,
  267. ).Result()
  268. // if error, continue for now
  269. if err != nil {
  270. continue
  271. }
  272. }
  273. }
  274. }