create_resource.go 15 KB

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