global_stream.go 12 KB

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