create_resource.go 15 KB

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