global_stream.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. package redis_stream
  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. "github.com/porter-dev/porter/internal/kubernetes"
  12. "github.com/porter-dev/porter/internal/kubernetes/envgroup"
  13. "gorm.io/gorm"
  14. redis "github.com/go-redis/redis/v8"
  15. "github.com/porter-dev/porter/api/server/shared/config"
  16. "github.com/porter-dev/porter/api/types"
  17. "github.com/porter-dev/porter/internal/models"
  18. "github.com/porter-dev/porter/internal/repository"
  19. )
  20. // GlobalStreamName is the name of the Redis stream for global operations
  21. const GlobalStreamName = "global"
  22. // GlobalStreamGroupName is the name of the Redis consumer group that this server
  23. // is a part of
  24. const GlobalStreamGroupName = "portersvr"
  25. // InitGlobalStream initializes the global stream if it does not exist, and the
  26. // global consumer group if it does not exist
  27. func InitGlobalStream(client *redis.Client) error {
  28. // determine if the stream exists
  29. x, err := client.Exists(
  30. context.Background(),
  31. GlobalStreamName,
  32. ).Result()
  33. // if it does not exist, create group and stream
  34. if x == 0 {
  35. _, err := client.XGroupCreateMkStream(
  36. context.Background(),
  37. GlobalStreamName,
  38. GlobalStreamGroupName,
  39. ">",
  40. ).Result()
  41. return err
  42. }
  43. // otherwise, check if the group exists
  44. xInfoGroups, err := client.XInfoGroups(
  45. context.Background(),
  46. GlobalStreamName,
  47. ).Result()
  48. // if error is not NOGROUP error, return
  49. if err != nil && !strings.Contains(err.Error(), "NOGROUP") {
  50. return err
  51. }
  52. for _, group := range xInfoGroups {
  53. // if the group exists, return with no error
  54. if group.Name == GlobalStreamGroupName {
  55. return nil
  56. }
  57. }
  58. // if the group does not exist, create it
  59. _, err = client.XGroupCreate(
  60. context.Background(),
  61. GlobalStreamName,
  62. GlobalStreamGroupName,
  63. "$",
  64. ).Result()
  65. return err
  66. }
  67. // ResourceCRUDHandler is a handler for updates to an infra resource
  68. type ResourceCRUDHandler interface {
  69. OnCreate(id uint) error
  70. }
  71. // GlobalStreamListener performs an XREADGROUP operation on a given stream and
  72. // updates models in the database as necessary
  73. func GlobalStreamListener(
  74. client *redis.Client,
  75. config *config.Config,
  76. repo repository.Repository,
  77. analyticsClient analytics.AnalyticsSegmentClient,
  78. errorChan chan error,
  79. ) {
  80. for {
  81. xstreams, err := client.XReadGroup(
  82. context.Background(),
  83. &redis.XReadGroupArgs{
  84. Group: GlobalStreamGroupName,
  85. Consumer: "portersvr-0", // just static consumer for now
  86. Streams: []string{GlobalStreamName, ">"},
  87. Block: 0,
  88. },
  89. ).Result()
  90. if err != nil {
  91. errorChan <- err
  92. return
  93. }
  94. // parse messages from the global stream
  95. for _, msg := range xstreams[0].Messages {
  96. // parse the id to identify the infra
  97. kind, projID, infraID, err := models.ParseUniqueName(fmt.Sprintf("%v", msg.Values["id"]))
  98. if fmt.Sprintf("%v", msg.Values["status"]) == "created" {
  99. infra, err := repo.Infra().ReadInfra(projID, infraID)
  100. if err != nil {
  101. continue
  102. }
  103. infra.Status = types.StatusCreated
  104. infra, err = repo.Infra().UpdateInfra(infra)
  105. if err != nil {
  106. continue
  107. }
  108. // create ECR/EKS
  109. if kind == string(types.InfraECR) {
  110. reg := &models.Registry{
  111. ProjectID: projID,
  112. AWSIntegrationID: infra.AWSIntegrationID,
  113. InfraID: infra.ID,
  114. }
  115. // parse raw data into ECR type
  116. dataString, ok := msg.Values["data"].(string)
  117. if ok {
  118. json.Unmarshal([]byte(dataString), reg)
  119. }
  120. awsInt, err := repo.AWSIntegration().ReadAWSIntegration(reg.ProjectID, reg.AWSIntegrationID)
  121. if err != nil {
  122. continue
  123. }
  124. sess, err := awsInt.GetSession()
  125. if err != nil {
  126. continue
  127. }
  128. ecrSvc := ecr.New(sess)
  129. output, err := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{})
  130. if err != nil {
  131. continue
  132. }
  133. reg.URL = *output.AuthorizationData[0].ProxyEndpoint
  134. reg, err = repo.Registry().CreateRegistry(reg)
  135. if err != nil {
  136. continue
  137. }
  138. analyticsClient.Track(analytics.RegistryProvisioningSuccessTrack(
  139. &analytics.RegistryProvisioningSuccessTrackOpts{
  140. RegistryScopedTrackOpts: analytics.GetRegistryScopedTrackOpts(infra.CreatedByUserID, infra.ProjectID, reg.ID),
  141. RegistryType: infra.Kind,
  142. InfraID: infra.ID,
  143. },
  144. ))
  145. } else if kind == string(types.InfraRDS) {
  146. // parse the last applied field to get the cluster id
  147. rdsRequest := &types.RDSInfraLastApplied{}
  148. err := json.Unmarshal(infra.LastApplied, rdsRequest)
  149. if err != nil {
  150. continue
  151. }
  152. database := &models.Database{
  153. Status: "running",
  154. }
  155. // parse raw data into ECR type
  156. dataString, ok := msg.Values["data"].(string)
  157. if ok {
  158. err = json.Unmarshal([]byte(dataString), database)
  159. if err != nil {
  160. }
  161. }
  162. database.Model = gorm.Model{}
  163. database.ProjectID = projID
  164. database.ClusterID = rdsRequest.ClusterID
  165. database.InfraID = infra.ID
  166. database, err = repo.Database().CreateDatabase(database)
  167. if err != nil {
  168. continue
  169. }
  170. infra.DatabaseID = database.ID
  171. infra, err = repo.Infra().UpdateInfra(infra)
  172. if err != nil {
  173. continue
  174. }
  175. err = createRDSEnvGroup(repo, config, infra, database, rdsRequest)
  176. if err != nil {
  177. continue
  178. }
  179. } else if kind == string(types.InfraEKS) {
  180. cluster := &models.Cluster{
  181. AuthMechanism: models.AWS,
  182. ProjectID: projID,
  183. AWSIntegrationID: infra.AWSIntegrationID,
  184. InfraID: infra.ID,
  185. }
  186. // parse raw data into ECR type
  187. dataString, ok := msg.Values["data"].(string)
  188. if ok {
  189. json.Unmarshal([]byte(dataString), cluster)
  190. }
  191. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  192. // if it matches the base64 regex, decode it
  193. caData := string(cluster.CertificateAuthorityData)
  194. if re.MatchString(caData) {
  195. decoded, err := base64.StdEncoding.DecodeString(caData)
  196. if err != nil {
  197. continue
  198. }
  199. cluster.CertificateAuthorityData = []byte(decoded)
  200. }
  201. cluster, err := repo.Cluster().CreateCluster(cluster)
  202. if err != nil {
  203. continue
  204. }
  205. analyticsClient.Track(analytics.ClusterProvisioningSuccessTrack(
  206. &analytics.ClusterProvisioningSuccessTrackOpts{
  207. ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(infra.CreatedByUserID, infra.ProjectID, cluster.ID),
  208. ClusterType: infra.Kind,
  209. InfraID: infra.ID,
  210. },
  211. ))
  212. } else if kind == string(types.InfraGCR) {
  213. reg := &models.Registry{
  214. ProjectID: projID,
  215. GCPIntegrationID: infra.GCPIntegrationID,
  216. InfraID: infra.ID,
  217. Name: "gcr-registry",
  218. }
  219. // parse raw data into ECR type
  220. dataString, ok := msg.Values["data"].(string)
  221. if ok {
  222. json.Unmarshal([]byte(dataString), reg)
  223. }
  224. reg, err = repo.Registry().CreateRegistry(reg)
  225. if err != nil {
  226. continue
  227. }
  228. analyticsClient.Track(analytics.RegistryProvisioningSuccessTrack(
  229. &analytics.RegistryProvisioningSuccessTrackOpts{
  230. RegistryScopedTrackOpts: analytics.GetRegistryScopedTrackOpts(infra.CreatedByUserID, infra.ProjectID, reg.ID),
  231. RegistryType: infra.Kind,
  232. InfraID: infra.ID,
  233. },
  234. ))
  235. } else if kind == string(types.InfraGKE) {
  236. cluster := &models.Cluster{
  237. AuthMechanism: models.GCP,
  238. ProjectID: projID,
  239. GCPIntegrationID: infra.GCPIntegrationID,
  240. InfraID: infra.ID,
  241. }
  242. // parse raw data into GKE type
  243. dataString, ok := msg.Values["data"].(string)
  244. if ok {
  245. json.Unmarshal([]byte(dataString), cluster)
  246. }
  247. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  248. // if it matches the base64 regex, decode it
  249. caData := string(cluster.CertificateAuthorityData)
  250. if re.MatchString(caData) {
  251. decoded, err := base64.StdEncoding.DecodeString(caData)
  252. if err != nil {
  253. continue
  254. }
  255. cluster.CertificateAuthorityData = []byte(decoded)
  256. }
  257. cluster, err := repo.Cluster().CreateCluster(cluster)
  258. if err != nil {
  259. continue
  260. }
  261. analyticsClient.Track(analytics.ClusterProvisioningSuccessTrack(
  262. &analytics.ClusterProvisioningSuccessTrackOpts{
  263. ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(infra.CreatedByUserID, infra.ProjectID, cluster.ID),
  264. ClusterType: infra.Kind,
  265. InfraID: infra.ID,
  266. },
  267. ))
  268. } else if kind == string(types.InfraDOCR) {
  269. reg := &models.Registry{
  270. ProjectID: projID,
  271. DOIntegrationID: infra.DOIntegrationID,
  272. InfraID: infra.ID,
  273. }
  274. // parse raw data into DOCR type
  275. dataString, ok := msg.Values["data"].(string)
  276. if ok {
  277. json.Unmarshal([]byte(dataString), reg)
  278. }
  279. reg, err = repo.Registry().CreateRegistry(reg)
  280. if err != nil {
  281. continue
  282. }
  283. analyticsClient.Track(analytics.RegistryProvisioningSuccessTrack(
  284. &analytics.RegistryProvisioningSuccessTrackOpts{
  285. RegistryScopedTrackOpts: analytics.GetRegistryScopedTrackOpts(infra.CreatedByUserID, infra.ProjectID, reg.ID),
  286. RegistryType: infra.Kind,
  287. InfraID: infra.ID,
  288. },
  289. ))
  290. } else if kind == string(types.InfraDOKS) {
  291. cluster := &models.Cluster{
  292. AuthMechanism: models.DO,
  293. ProjectID: projID,
  294. DOIntegrationID: infra.DOIntegrationID,
  295. InfraID: infra.ID,
  296. }
  297. // parse raw data into GKE type
  298. dataString, ok := msg.Values["data"].(string)
  299. if ok {
  300. json.Unmarshal([]byte(dataString), cluster)
  301. }
  302. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  303. // if it matches the base64 regex, decode it
  304. caData := string(cluster.CertificateAuthorityData)
  305. if re.MatchString(caData) {
  306. decoded, err := base64.StdEncoding.DecodeString(caData)
  307. if err != nil {
  308. continue
  309. }
  310. cluster.CertificateAuthorityData = []byte(decoded)
  311. }
  312. cluster, err := repo.Cluster().CreateCluster(cluster)
  313. if err != nil {
  314. continue
  315. }
  316. analyticsClient.Track(analytics.ClusterProvisioningSuccessTrack(
  317. &analytics.ClusterProvisioningSuccessTrackOpts{
  318. ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(infra.CreatedByUserID, infra.ProjectID, cluster.ID),
  319. ClusterType: infra.Kind,
  320. InfraID: infra.ID,
  321. },
  322. ))
  323. }
  324. } else if fmt.Sprintf("%v", msg.Values["status"]) == "error" {
  325. infra, err := repo.Infra().ReadInfra(projID, infraID)
  326. if err != nil {
  327. continue
  328. }
  329. infra.Status = types.StatusError
  330. infra, err = repo.Infra().UpdateInfra(infra)
  331. if err != nil {
  332. continue
  333. }
  334. if infra.Kind == types.InfraDOKS || infra.Kind == types.InfraGKE || infra.Kind == types.InfraEKS {
  335. analyticsClient.Track(analytics.ClusterProvisioningErrorTrack(
  336. &analytics.ClusterProvisioningErrorTrackOpts{
  337. ProjectScopedTrackOpts: analytics.GetProjectScopedTrackOpts(infra.CreatedByUserID, infra.ProjectID),
  338. ClusterType: infra.Kind,
  339. InfraID: infra.ID,
  340. },
  341. ))
  342. } else if infra.Kind == types.InfraDOCR || infra.Kind == types.InfraGCR || infra.Kind == types.InfraECR {
  343. analyticsClient.Track(analytics.RegistryProvisioningErrorTrack(
  344. &analytics.RegistryProvisioningErrorTrackOpts{
  345. ProjectScopedTrackOpts: analytics.GetProjectScopedTrackOpts(infra.CreatedByUserID, infra.ProjectID),
  346. RegistryType: infra.Kind,
  347. InfraID: infra.ID,
  348. },
  349. ))
  350. }
  351. } else if fmt.Sprintf("%v", msg.Values["status"]) == "destroyed" {
  352. infra, err := repo.Infra().ReadInfra(projID, infraID)
  353. if err != nil {
  354. continue
  355. }
  356. infra.Status = types.StatusDestroyed
  357. infra, err = repo.Infra().UpdateInfra(infra)
  358. if err != nil {
  359. continue
  360. }
  361. if infra.Kind == types.InfraDOKS || infra.Kind == types.InfraGKE || infra.Kind == types.InfraEKS {
  362. analyticsClient.Track(analytics.ClusterDestroyingSuccessTrack(
  363. &analytics.ClusterDestroyingSuccessTrackOpts{
  364. ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(infra.CreatedByUserID, infra.ProjectID, 0),
  365. ClusterType: infra.Kind,
  366. InfraID: infra.ID,
  367. },
  368. ))
  369. } else if infra.Kind == types.InfraRDS && infra.DatabaseID != 0 {
  370. rdsRequest := &types.RDSInfraLastApplied{}
  371. err := json.Unmarshal(infra.LastApplied, rdsRequest)
  372. if err != nil {
  373. continue
  374. }
  375. database, err := repo.Database().ReadDatabase(infra.ProjectID, rdsRequest.ClusterID, infra.DatabaseID)
  376. if err != nil {
  377. continue
  378. }
  379. err = deleteRDSEnvGroup(repo, config, infra, database, rdsRequest)
  380. if err != nil {
  381. continue
  382. }
  383. // delete the database
  384. err = repo.Database().DeleteDatabase(infra.ProjectID, rdsRequest.ClusterID, infra.DatabaseID)
  385. if err != nil {
  386. continue
  387. }
  388. }
  389. }
  390. // acknowledge the message as read
  391. _, err = client.XAck(
  392. context.Background(),
  393. GlobalStreamName,
  394. GlobalStreamGroupName,
  395. msg.ID,
  396. ).Result()
  397. // if error, continue for now
  398. if err != nil {
  399. continue
  400. }
  401. }
  402. }
  403. }
  404. func createRDSEnvGroup(repo repository.Repository, config *config.Config, infra *models.Infra, database *models.Database, rdsConfig *types.RDSInfraLastApplied) error {
  405. cluster, err := repo.Cluster().ReadCluster(infra.ProjectID, rdsConfig.ClusterID)
  406. if err != nil {
  407. return err
  408. }
  409. ooc := &kubernetes.OutOfClusterConfig{
  410. Repo: config.Repo,
  411. DigitalOceanOAuth: config.DOConf,
  412. Cluster: cluster,
  413. }
  414. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  415. if err != nil {
  416. return fmt.Errorf("failed to get agent: %s", err.Error())
  417. }
  418. // split the instance endpoint on the port
  419. port := "5432"
  420. host := database.InstanceEndpoint
  421. if strArr := strings.Split(database.InstanceEndpoint, ":"); len(strArr) == 2 {
  422. host = strArr[0]
  423. port = strArr[1]
  424. }
  425. _, err = envgroup.CreateEnvGroup(agent, types.ConfigMapInput{
  426. Name: fmt.Sprintf("rds-credentials-%s", rdsConfig.DBName),
  427. Namespace: rdsConfig.Namespace,
  428. Variables: map[string]string{},
  429. SecretVariables: map[string]string{
  430. "PGPORT": port,
  431. "PGHOST": host,
  432. "PGPASSWORD": rdsConfig.Password,
  433. "PGUSER": rdsConfig.Username,
  434. },
  435. })
  436. if err != nil {
  437. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  438. }
  439. return nil
  440. }
  441. func deleteRDSEnvGroup(repo repository.Repository, config *config.Config, infra *models.Infra, database *models.Database, rdsConfig *types.RDSInfraLastApplied) error {
  442. cluster, err := repo.Cluster().ReadCluster(infra.ProjectID, rdsConfig.ClusterID)
  443. if err != nil {
  444. return err
  445. }
  446. ooc := &kubernetes.OutOfClusterConfig{
  447. Repo: config.Repo,
  448. DigitalOceanOAuth: config.DOConf,
  449. Cluster: cluster,
  450. }
  451. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  452. if err != nil {
  453. return fmt.Errorf("failed to get agent: %s", err.Error())
  454. }
  455. err = envgroup.DeleteEnvGroup(agent, fmt.Sprintf("rds-credentials-%s", rdsConfig.DBName), rdsConfig.Namespace)
  456. if err != nil {
  457. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  458. }
  459. return nil
  460. }