create_resource.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. MonitorHelmReleases: true,
  240. }
  241. switch infra.Kind {
  242. case types.InfraEKS:
  243. res.AuthMechanism = models.AWS
  244. res.AWSIntegrationID = infra.AWSIntegrationID
  245. case types.InfraGKE:
  246. res.AuthMechanism = models.GCP
  247. res.GCPIntegrationID = infra.GCPIntegrationID
  248. case types.InfraDOKS:
  249. res.AuthMechanism = models.DO
  250. res.DOIntegrationID = infra.DOIntegrationID
  251. case types.InfraAKS:
  252. res.AuthMechanism = models.Azure
  253. res.AzureIntegrationID = infra.AzureIntegrationID
  254. }
  255. return res
  256. }
  257. func transformClusterCAData(ca []byte) ([]byte, error) {
  258. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  259. // if it matches the base64 regex, decode it
  260. caData := string(ca)
  261. if re.MatchString(caData) {
  262. decoded, err := base64.StdEncoding.DecodeString(caData)
  263. if err != nil {
  264. return nil, err
  265. }
  266. return []byte(decoded), nil
  267. }
  268. // otherwise just return the CA
  269. return ca, nil
  270. }
  271. func createDOCRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  272. reg := &models.Registry{
  273. ProjectID: infra.ProjectID,
  274. DOIntegrationID: infra.DOIntegrationID,
  275. InfraID: infra.ID,
  276. URL: output["url"].(string),
  277. Name: output["name"].(string),
  278. }
  279. return config.Repo.Registry().CreateRegistry(reg)
  280. }
  281. func createGCRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  282. reg := &models.Registry{
  283. ProjectID: infra.ProjectID,
  284. GCPIntegrationID: infra.GCPIntegrationID,
  285. InfraID: infra.ID,
  286. URL: output["url"].(string),
  287. Name: "gcr-registry",
  288. }
  289. return config.Repo.Registry().CreateRegistry(reg)
  290. }
  291. func createGARRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  292. reg := &models.Registry{
  293. ProjectID: infra.ProjectID,
  294. GCPIntegrationID: infra.GCPIntegrationID,
  295. InfraID: infra.ID,
  296. URL: output["url"].(string),
  297. Name: "gar-registry",
  298. }
  299. return config.Repo.Registry().CreateRegistry(reg)
  300. }
  301. func createACRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  302. reg := &models.Registry{
  303. ProjectID: infra.ProjectID,
  304. AzureIntegrationID: infra.AzureIntegrationID,
  305. InfraID: infra.ID,
  306. URL: output["url"].(string),
  307. Name: output["name"].(string),
  308. }
  309. return config.Repo.Registry().CreateRegistry(reg)
  310. }
  311. func createRDSEnvGroup(config *config.Config, infra *models.Infra, database *models.Database, lastApplied map[string]interface{}) error {
  312. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  313. if err != nil {
  314. return err
  315. }
  316. ooc := &kubernetes.OutOfClusterConfig{
  317. Repo: config.Repo,
  318. DigitalOceanOAuth: config.DOConf,
  319. Cluster: cluster,
  320. }
  321. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  322. if err != nil {
  323. return fmt.Errorf("failed to get agent: %s", err.Error())
  324. }
  325. // split the instance endpoint on the port
  326. port := "5432"
  327. host := database.InstanceEndpoint
  328. if strArr := strings.Split(database.InstanceEndpoint, ":"); len(strArr) == 2 {
  329. host = strArr[0]
  330. port = strArr[1]
  331. }
  332. _, err = envgroup.CreateEnvGroup(agent, types.ConfigMapInput{
  333. Name: fmt.Sprintf("rds-credentials-%s", lastApplied["db_name"].(string)),
  334. Namespace: "default",
  335. Variables: map[string]string{},
  336. SecretVariables: map[string]string{
  337. "PGPORT": port,
  338. "PGHOST": host,
  339. "PGPASSWORD": lastApplied["db_passwd"].(string),
  340. "PGUSER": lastApplied["db_user"].(string),
  341. },
  342. })
  343. if err != nil {
  344. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  345. }
  346. return nil
  347. }
  348. func deleteRDSEnvGroup(config *config.Config, infra *models.Infra, lastApplied map[string]interface{}) error {
  349. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  350. if err != nil {
  351. return err
  352. }
  353. ooc := &kubernetes.OutOfClusterConfig{
  354. Repo: config.Repo,
  355. DigitalOceanOAuth: config.DOConf,
  356. Cluster: cluster,
  357. }
  358. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  359. if err != nil {
  360. return fmt.Errorf("failed to get agent: %s", err.Error())
  361. }
  362. err = envgroup.DeleteEnvGroup(agent, fmt.Sprintf("rds-credentials-%s", lastApplied["db_name"].(string)), "default")
  363. if err != nil {
  364. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  365. }
  366. return nil
  367. }
  368. func createS3EnvGroup(config *config.Config, infra *models.Infra, lastApplied map[string]interface{}, output map[string]interface{}) error {
  369. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  370. if err != nil {
  371. return err
  372. }
  373. ooc := &kubernetes.OutOfClusterConfig{
  374. Repo: config.Repo,
  375. DigitalOceanOAuth: config.DOConf,
  376. Cluster: cluster,
  377. }
  378. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  379. if err != nil {
  380. return fmt.Errorf("failed to get agent: %s", err.Error())
  381. }
  382. // split the instance endpoint on the port
  383. _, err = envgroup.CreateEnvGroup(agent, types.ConfigMapInput{
  384. Name: fmt.Sprintf("s3-credentials-%s", lastApplied["bucket_name"].(string)),
  385. Namespace: "default",
  386. Variables: map[string]string{},
  387. SecretVariables: map[string]string{
  388. "S3_AWS_ACCESS_KEY_ID": output["s3_aws_access_key_id"].(string),
  389. "S3_AWS_SECRET_KEY": output["s3_aws_secret_key"].(string),
  390. "S3_BUCKET_NAME": output["s3_bucket_name"].(string),
  391. },
  392. })
  393. if err != nil {
  394. return fmt.Errorf("failed to create S3 env group: %s", err.Error())
  395. }
  396. return nil
  397. }
  398. func deleteS3EnvGroup(config *config.Config, infra *models.Infra, lastApplied map[string]interface{}) error {
  399. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  400. if err != nil {
  401. return err
  402. }
  403. ooc := &kubernetes.OutOfClusterConfig{
  404. Repo: config.Repo,
  405. DigitalOceanOAuth: config.DOConf,
  406. Cluster: cluster,
  407. }
  408. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  409. if err != nil {
  410. return fmt.Errorf("failed to get agent: %s", err.Error())
  411. }
  412. err = envgroup.DeleteEnvGroup(agent, fmt.Sprintf("s3-credentials-%s", lastApplied["bucket_name"].(string)), "default")
  413. if err != nil {
  414. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  415. }
  416. return nil
  417. }