create_resource.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. package state
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "regexp"
  10. "strings"
  11. "github.com/aws/aws-sdk-go-v2/service/ecr"
  12. "github.com/porter-dev/porter/api/server/shared"
  13. "github.com/porter-dev/porter/api/server/shared/apierrors"
  14. "github.com/porter-dev/porter/api/types"
  15. "github.com/porter-dev/porter/internal/analytics"
  16. "github.com/porter-dev/porter/internal/kubernetes"
  17. "github.com/porter-dev/porter/internal/kubernetes/envgroup"
  18. "github.com/porter-dev/porter/internal/models"
  19. "github.com/porter-dev/porter/provisioner/integrations/redis_stream"
  20. "github.com/porter-dev/porter/provisioner/server/config"
  21. ptypes "github.com/porter-dev/porter/provisioner/types"
  22. "gorm.io/gorm"
  23. )
  24. type CreateResourceHandler struct {
  25. Config *config.Config
  26. decoderValidator shared.RequestDecoderValidator
  27. }
  28. func NewCreateResourceHandler(
  29. config *config.Config,
  30. ) *CreateResourceHandler {
  31. return &CreateResourceHandler{
  32. Config: config,
  33. decoderValidator: shared.NewDefaultRequestDecoderValidator(config.Logger, config.Alerter),
  34. }
  35. }
  36. func (c *CreateResourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  37. // read the infra from the attached scope
  38. infra, _ := r.Context().Value(types.InfraScope).(*models.Infra)
  39. operation, _ := r.Context().Value(types.OperationScope).(*models.Operation)
  40. req := &ptypes.CreateResourceRequest{}
  41. if ok := c.decoderValidator.DecodeAndValidate(w, r, req); !ok {
  42. return
  43. }
  44. // update the operation to indicate completion
  45. operation.Status = "completed"
  46. operation, err := c.Config.Repo.Infra().UpdateOperation(operation)
  47. if err != nil {
  48. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  49. return
  50. }
  51. // push to the operation stream
  52. err = redis_stream.SendOperationCompleted(c.Config.RedisClient, infra, operation)
  53. if err != nil {
  54. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  55. return
  56. }
  57. // push to the global stream
  58. err = redis_stream.PushToGlobalStream(c.Config.RedisClient, infra, operation, "created")
  59. if err != nil {
  60. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  61. return
  62. }
  63. // update the infra to indicate completion
  64. infra.Status = "created"
  65. infra, err = c.Config.Repo.Infra().UpdateInfra(infra)
  66. if err != nil {
  67. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  68. return
  69. }
  70. // switch on the kind of resource and write the corresponding objects to the database
  71. switch req.Kind {
  72. case string(types.InfraEKS), string(types.InfraDOKS), string(types.InfraGKE), string(types.InfraAKS):
  73. var cluster *models.Cluster
  74. cluster, err = createCluster(c.Config, infra, operation, req.Output)
  75. if cluster != nil {
  76. c.Config.AnalyticsClient.Track(analytics.ClusterProvisioningSuccessTrack(
  77. &analytics.ClusterProvisioningSuccessTrackOpts{
  78. ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(0, infra.ProjectID, cluster.ID),
  79. ClusterType: infra.Kind,
  80. InfraID: infra.ID,
  81. },
  82. ))
  83. }
  84. case string(types.InfraECR):
  85. _, err = createECRRegistry(c.Config, infra, operation, req.Output)
  86. case string(types.InfraRDS):
  87. _, err = createRDSDatabase(c.Config, infra, operation, req.Output)
  88. case string(types.InfraS3):
  89. err = createS3Bucket(c.Config, infra, operation, req.Output)
  90. case string(types.InfraDOCR):
  91. _, err = createDOCRRegistry(c.Config, infra, operation, req.Output)
  92. case string(types.InfraGCR):
  93. _, err = createGCRRegistry(c.Config, infra, operation, req.Output)
  94. case string(types.InfraGAR):
  95. _, err = createGARRegistry(c.Config, infra, operation, req.Output)
  96. case string(types.InfraACR):
  97. _, err = createACRRegistry(c.Config, infra, operation, req.Output)
  98. }
  99. if err != nil {
  100. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  101. return
  102. }
  103. }
  104. func createECRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  105. ctx := context.Background()
  106. reg := &models.Registry{
  107. ProjectID: infra.ProjectID,
  108. AWSIntegrationID: infra.AWSIntegrationID,
  109. InfraID: infra.ID,
  110. Name: output["name"].(string),
  111. }
  112. // parse raw data into ECR type
  113. awsInt, err := config.Repo.AWSIntegration().ReadAWSIntegration(reg.ProjectID, reg.AWSIntegrationID)
  114. if err != nil {
  115. return nil, err
  116. }
  117. svc := ecr.NewFromConfig(awsInt.Config())
  118. authOutput, err := svc.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})
  119. if err != nil {
  120. return nil, err
  121. }
  122. reg.URL = *authOutput.AuthorizationData[0].ProxyEndpoint
  123. reg, err = config.Repo.Registry().CreateRegistry(reg)
  124. if err != nil {
  125. return nil, err
  126. }
  127. return reg, nil
  128. }
  129. func createRDSDatabase(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Database, error) {
  130. // check for infra id being 0 as a safeguard so that all non-provisioned
  131. // clusters are not matched by read
  132. if infra.ID == 0 {
  133. return nil, fmt.Errorf("infra id cannot be 0")
  134. }
  135. var database *models.Database
  136. var err error
  137. var isNotFound bool
  138. database, err = config.Repo.Database().ReadDatabaseByInfraID(infra.ProjectID, infra.ID)
  139. isNotFound = err != nil && errors.Is(err, gorm.ErrRecordNotFound)
  140. if isNotFound {
  141. database = &models.Database{
  142. ProjectID: infra.ProjectID,
  143. ClusterID: infra.ParentClusterID,
  144. InfraID: infra.ID,
  145. Status: "Running",
  146. }
  147. } else if err != nil {
  148. return nil, err
  149. }
  150. database.InstanceID = output["rds_instance_id"].(string)
  151. database.InstanceEndpoint = output["rds_connection_endpoint"].(string)
  152. database.InstanceName = output["rds_instance_name"].(string)
  153. if isNotFound {
  154. database, err = config.Repo.Database().CreateDatabase(database)
  155. } else {
  156. database, err = config.Repo.Database().UpdateDatabase(database)
  157. }
  158. infra.DatabaseID = database.ID
  159. infra, err = config.Repo.Infra().UpdateInfra(infra)
  160. if err != nil {
  161. return nil, err
  162. }
  163. lastApplied := make(map[string]interface{})
  164. err = json.Unmarshal(operation.LastApplied, &lastApplied)
  165. if err != nil {
  166. return nil, err
  167. }
  168. err = createRDSEnvGroup(config, infra, database, lastApplied)
  169. if err != nil {
  170. return nil, err
  171. }
  172. return database, nil
  173. }
  174. func createS3Bucket(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) error {
  175. lastApplied := make(map[string]interface{})
  176. err := json.Unmarshal(operation.LastApplied, &lastApplied)
  177. if err != nil {
  178. return err
  179. }
  180. return createS3EnvGroup(config, infra, lastApplied, output)
  181. }
  182. func createCluster(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Cluster, error) {
  183. // check for infra id being 0 as a safeguard so that all non-provisioned
  184. // clusters are not matched by read
  185. if infra.ID == 0 {
  186. return nil, fmt.Errorf("infra id cannot be 0")
  187. }
  188. var cluster *models.Cluster
  189. var err error
  190. var isNotFound bool
  191. // look for cluster matching infra in database; if the cluster already exists, update the cluster but
  192. // don't add it again
  193. cluster, err = config.Repo.Cluster().ReadClusterByInfraID(infra.ProjectID, infra.ID)
  194. isNotFound = err != nil && errors.Is(err, gorm.ErrRecordNotFound)
  195. if isNotFound {
  196. cluster = getNewCluster(infra)
  197. } else if err != nil {
  198. return nil, err
  199. }
  200. caData, err := transformClusterCAData([]byte(output["cluster_ca_data"].(string)))
  201. if err != nil {
  202. return nil, err
  203. }
  204. // if cluster_token is output and infra is azure, update the azure integration
  205. if _, exists := output["cluster_token"]; exists && infra.AzureIntegrationID != 0 {
  206. azInt, err := config.Repo.AzureIntegration().ReadAzureIntegration(infra.ProjectID, infra.AzureIntegrationID)
  207. if err != nil {
  208. return nil, err
  209. }
  210. azInt.AKSPassword = []byte(output["cluster_token"].(string))
  211. azInt, err = config.Repo.AzureIntegration().OverwriteAzureIntegration(azInt)
  212. if err != nil {
  213. return nil, err
  214. }
  215. }
  216. // only update the cluster name if this is during creation - we don't want to overwrite the cluster name
  217. // which may have been manually set
  218. if isNotFound {
  219. cluster.Name = output["cluster_name"].(string)
  220. }
  221. cluster.Server = output["cluster_endpoint"].(string)
  222. cluster.CertificateAuthorityData = caData
  223. if isNotFound {
  224. cluster, err = config.Repo.Cluster().CreateCluster(cluster)
  225. } else {
  226. cluster, err = config.Repo.Cluster().UpdateCluster(cluster)
  227. }
  228. if err != nil {
  229. return nil, err
  230. }
  231. return cluster, nil
  232. }
  233. func getNewCluster(infra *models.Infra) *models.Cluster {
  234. res := &models.Cluster{
  235. ProjectID: infra.ProjectID,
  236. InfraID: infra.ID,
  237. MonitorHelmReleases: true,
  238. }
  239. switch infra.Kind {
  240. case types.InfraEKS:
  241. res.AuthMechanism = models.AWS
  242. res.AWSIntegrationID = infra.AWSIntegrationID
  243. case types.InfraGKE:
  244. res.AuthMechanism = models.GCP
  245. res.GCPIntegrationID = infra.GCPIntegrationID
  246. case types.InfraDOKS:
  247. res.AuthMechanism = models.DO
  248. res.DOIntegrationID = infra.DOIntegrationID
  249. case types.InfraAKS:
  250. res.AuthMechanism = models.Azure
  251. res.AzureIntegrationID = infra.AzureIntegrationID
  252. }
  253. return res
  254. }
  255. func transformClusterCAData(ca []byte) ([]byte, error) {
  256. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  257. // if it matches the base64 regex, decode it
  258. caData := string(ca)
  259. if re.MatchString(caData) {
  260. decoded, err := base64.StdEncoding.DecodeString(caData)
  261. if err != nil {
  262. return nil, err
  263. }
  264. return []byte(decoded), nil
  265. }
  266. // otherwise just return the CA
  267. return ca, nil
  268. }
  269. func createDOCRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  270. reg := &models.Registry{
  271. ProjectID: infra.ProjectID,
  272. DOIntegrationID: infra.DOIntegrationID,
  273. InfraID: infra.ID,
  274. URL: output["url"].(string),
  275. Name: output["name"].(string),
  276. }
  277. return config.Repo.Registry().CreateRegistry(reg)
  278. }
  279. func createGCRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  280. reg := &models.Registry{
  281. ProjectID: infra.ProjectID,
  282. GCPIntegrationID: infra.GCPIntegrationID,
  283. InfraID: infra.ID,
  284. URL: output["url"].(string),
  285. Name: "gcr-registry",
  286. }
  287. return config.Repo.Registry().CreateRegistry(reg)
  288. }
  289. func createGARRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  290. reg := &models.Registry{
  291. ProjectID: infra.ProjectID,
  292. GCPIntegrationID: infra.GCPIntegrationID,
  293. InfraID: infra.ID,
  294. URL: output["url"].(string),
  295. Name: "gar-registry",
  296. }
  297. return config.Repo.Registry().CreateRegistry(reg)
  298. }
  299. func createACRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  300. reg := &models.Registry{
  301. ProjectID: infra.ProjectID,
  302. AzureIntegrationID: infra.AzureIntegrationID,
  303. InfraID: infra.ID,
  304. URL: output["url"].(string),
  305. Name: output["name"].(string),
  306. }
  307. return config.Repo.Registry().CreateRegistry(reg)
  308. }
  309. func createRDSEnvGroup(config *config.Config, infra *models.Infra, database *models.Database, lastApplied map[string]interface{}) error {
  310. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  311. if err != nil {
  312. return err
  313. }
  314. ooc := &kubernetes.OutOfClusterConfig{
  315. Repo: config.Repo,
  316. DigitalOceanOAuth: config.DOConf,
  317. Cluster: cluster,
  318. }
  319. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  320. if err != nil {
  321. return fmt.Errorf("failed to get agent: %s", err.Error())
  322. }
  323. // split the instance endpoint on the port
  324. port := "5432"
  325. host := database.InstanceEndpoint
  326. if strArr := strings.Split(database.InstanceEndpoint, ":"); len(strArr) == 2 {
  327. host = strArr[0]
  328. port = strArr[1]
  329. }
  330. _, err = envgroup.CreateEnvGroup(agent, types.ConfigMapInput{
  331. Name: fmt.Sprintf("rds-credentials-%s", lastApplied["db_name"].(string)),
  332. Namespace: "default",
  333. Variables: map[string]string{},
  334. SecretVariables: map[string]string{
  335. "PGPORT": port,
  336. "PGHOST": host,
  337. "PGPASSWORD": lastApplied["db_passwd"].(string),
  338. "PGUSER": lastApplied["db_user"].(string),
  339. },
  340. })
  341. if err != nil {
  342. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  343. }
  344. return nil
  345. }
  346. func deleteRDSEnvGroup(config *config.Config, infra *models.Infra, lastApplied map[string]interface{}) error {
  347. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  348. if err != nil {
  349. return err
  350. }
  351. ooc := &kubernetes.OutOfClusterConfig{
  352. Repo: config.Repo,
  353. DigitalOceanOAuth: config.DOConf,
  354. Cluster: cluster,
  355. }
  356. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  357. if err != nil {
  358. return fmt.Errorf("failed to get agent: %s", err.Error())
  359. }
  360. err = envgroup.DeleteEnvGroup(agent, fmt.Sprintf("rds-credentials-%s", lastApplied["db_name"].(string)), "default")
  361. if err != nil {
  362. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  363. }
  364. return nil
  365. }
  366. func createS3EnvGroup(config *config.Config, infra *models.Infra, lastApplied map[string]interface{}, output map[string]interface{}) error {
  367. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  368. if err != nil {
  369. return err
  370. }
  371. ooc := &kubernetes.OutOfClusterConfig{
  372. Repo: config.Repo,
  373. DigitalOceanOAuth: config.DOConf,
  374. Cluster: cluster,
  375. }
  376. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  377. if err != nil {
  378. return fmt.Errorf("failed to get agent: %s", err.Error())
  379. }
  380. // split the instance endpoint on the port
  381. _, err = envgroup.CreateEnvGroup(agent, types.ConfigMapInput{
  382. Name: fmt.Sprintf("s3-credentials-%s", lastApplied["bucket_name"].(string)),
  383. Namespace: "default",
  384. Variables: map[string]string{},
  385. SecretVariables: map[string]string{
  386. "S3_AWS_ACCESS_KEY_ID": output["s3_aws_access_key_id"].(string),
  387. "S3_AWS_SECRET_KEY": output["s3_aws_secret_key"].(string),
  388. "S3_BUCKET_NAME": output["s3_bucket_name"].(string),
  389. },
  390. })
  391. if err != nil {
  392. return fmt.Errorf("failed to create S3 env group: %s", err.Error())
  393. }
  394. return nil
  395. }
  396. func deleteS3EnvGroup(config *config.Config, infra *models.Infra, lastApplied map[string]interface{}) error {
  397. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  398. if err != nil {
  399. return err
  400. }
  401. ooc := &kubernetes.OutOfClusterConfig{
  402. Repo: config.Repo,
  403. DigitalOceanOAuth: config.DOConf,
  404. Cluster: cluster,
  405. }
  406. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  407. if err != nil {
  408. return fmt.Errorf("failed to get agent: %s", err.Error())
  409. }
  410. err = envgroup.DeleteEnvGroup(agent, fmt.Sprintf("s3-credentials-%s", lastApplied["bucket_name"].(string)), "default")
  411. if err != nil {
  412. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  413. }
  414. return nil
  415. }