create_resource.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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.InfraACR):
  94. _, err = createACRRegistry(c.Config, infra, operation, req.Output)
  95. }
  96. if err != nil {
  97. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  98. return
  99. }
  100. }
  101. func createECRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  102. reg := &models.Registry{
  103. ProjectID: infra.ProjectID,
  104. AWSIntegrationID: infra.AWSIntegrationID,
  105. InfraID: infra.ID,
  106. Name: output["name"].(string),
  107. }
  108. // parse raw data into ECR type
  109. awsInt, err := config.Repo.AWSIntegration().ReadAWSIntegration(reg.ProjectID, reg.AWSIntegrationID)
  110. if err != nil {
  111. return nil, err
  112. }
  113. sess, err := awsInt.GetSession()
  114. if err != nil {
  115. return nil, err
  116. }
  117. ecrSvc := ecr.New(sess)
  118. authOutput, err := ecrSvc.GetAuthorizationToken(&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. cluster.Name = output["cluster_name"].(string)
  217. cluster.Server = output["cluster_endpoint"].(string)
  218. cluster.CertificateAuthorityData = caData
  219. if isNotFound {
  220. cluster, err = config.Repo.Cluster().CreateCluster(cluster)
  221. } else {
  222. cluster, err = config.Repo.Cluster().UpdateCluster(cluster)
  223. }
  224. if err != nil {
  225. return nil, err
  226. }
  227. return cluster, nil
  228. }
  229. func getNewCluster(infra *models.Infra) *models.Cluster {
  230. res := &models.Cluster{
  231. ProjectID: infra.ProjectID,
  232. InfraID: infra.ID,
  233. }
  234. switch infra.Kind {
  235. case types.InfraEKS:
  236. res.AuthMechanism = models.AWS
  237. res.AWSIntegrationID = infra.AWSIntegrationID
  238. case types.InfraGKE:
  239. res.AuthMechanism = models.GCP
  240. res.GCPIntegrationID = infra.GCPIntegrationID
  241. case types.InfraDOKS:
  242. res.AuthMechanism = models.DO
  243. res.DOIntegrationID = infra.DOIntegrationID
  244. case types.InfraAKS:
  245. res.AuthMechanism = models.Azure
  246. res.AzureIntegrationID = infra.AzureIntegrationID
  247. }
  248. return res
  249. }
  250. func transformClusterCAData(ca []byte) ([]byte, error) {
  251. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  252. // if it matches the base64 regex, decode it
  253. caData := string(ca)
  254. if re.MatchString(caData) {
  255. decoded, err := base64.StdEncoding.DecodeString(caData)
  256. if err != nil {
  257. return nil, err
  258. }
  259. return []byte(decoded), nil
  260. }
  261. // otherwise just return the CA
  262. return ca, nil
  263. }
  264. func createDOCRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  265. reg := &models.Registry{
  266. ProjectID: infra.ProjectID,
  267. DOIntegrationID: infra.DOIntegrationID,
  268. InfraID: infra.ID,
  269. URL: output["url"].(string),
  270. Name: output["name"].(string),
  271. }
  272. return config.Repo.Registry().CreateRegistry(reg)
  273. }
  274. func createGCRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  275. reg := &models.Registry{
  276. ProjectID: infra.ProjectID,
  277. GCPIntegrationID: infra.GCPIntegrationID,
  278. InfraID: infra.ID,
  279. URL: output["url"].(string),
  280. Name: "gcr-registry",
  281. }
  282. return config.Repo.Registry().CreateRegistry(reg)
  283. }
  284. func createACRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  285. reg := &models.Registry{
  286. ProjectID: infra.ProjectID,
  287. AzureIntegrationID: infra.AzureIntegrationID,
  288. InfraID: infra.ID,
  289. URL: output["url"].(string),
  290. Name: output["name"].(string),
  291. }
  292. return config.Repo.Registry().CreateRegistry(reg)
  293. }
  294. func createRDSEnvGroup(config *config.Config, infra *models.Infra, database *models.Database, lastApplied map[string]interface{}) error {
  295. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  296. if err != nil {
  297. return err
  298. }
  299. ooc := &kubernetes.OutOfClusterConfig{
  300. Repo: config.Repo,
  301. DigitalOceanOAuth: config.DOConf,
  302. Cluster: cluster,
  303. }
  304. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  305. if err != nil {
  306. return fmt.Errorf("failed to get agent: %s", err.Error())
  307. }
  308. // split the instance endpoint on the port
  309. port := "5432"
  310. host := database.InstanceEndpoint
  311. if strArr := strings.Split(database.InstanceEndpoint, ":"); len(strArr) == 2 {
  312. host = strArr[0]
  313. port = strArr[1]
  314. }
  315. _, err = envgroup.CreateEnvGroup(agent, types.ConfigMapInput{
  316. Name: fmt.Sprintf("rds-credentials-%s", lastApplied["db_name"].(string)),
  317. Namespace: "default",
  318. Variables: map[string]string{},
  319. SecretVariables: map[string]string{
  320. "PGPORT": port,
  321. "PGHOST": host,
  322. "PGPASSWORD": lastApplied["db_passwd"].(string),
  323. "PGUSER": lastApplied["db_user"].(string),
  324. },
  325. })
  326. if err != nil {
  327. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  328. }
  329. return nil
  330. }
  331. func deleteRDSEnvGroup(config *config.Config, infra *models.Infra, lastApplied map[string]interface{}) error {
  332. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  333. if err != nil {
  334. return err
  335. }
  336. ooc := &kubernetes.OutOfClusterConfig{
  337. Repo: config.Repo,
  338. DigitalOceanOAuth: config.DOConf,
  339. Cluster: cluster,
  340. }
  341. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  342. if err != nil {
  343. return fmt.Errorf("failed to get agent: %s", err.Error())
  344. }
  345. err = envgroup.DeleteEnvGroup(agent, fmt.Sprintf("rds-credentials-%s", lastApplied["db_name"].(string)), "default")
  346. if err != nil {
  347. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  348. }
  349. return nil
  350. }
  351. func createS3EnvGroup(config *config.Config, infra *models.Infra, lastApplied map[string]interface{}, output map[string]interface{}) error {
  352. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  353. if err != nil {
  354. return err
  355. }
  356. ooc := &kubernetes.OutOfClusterConfig{
  357. Repo: config.Repo,
  358. DigitalOceanOAuth: config.DOConf,
  359. Cluster: cluster,
  360. }
  361. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  362. if err != nil {
  363. return fmt.Errorf("failed to get agent: %s", err.Error())
  364. }
  365. // split the instance endpoint on the port
  366. _, err = envgroup.CreateEnvGroup(agent, types.ConfigMapInput{
  367. Name: fmt.Sprintf("s3-credentials-%s", lastApplied["bucket_name"].(string)),
  368. Namespace: "default",
  369. Variables: map[string]string{},
  370. SecretVariables: map[string]string{
  371. "S3_AWS_ACCESS_KEY_ID": output["s3_aws_access_key_id"].(string),
  372. "S3_AWS_SECRET_KEY": output["s3_aws_secret_key"].(string),
  373. "S3_BUCKET_NAME": output["s3_bucket_name"].(string),
  374. },
  375. })
  376. if err != nil {
  377. return fmt.Errorf("failed to create S3 env group: %s", err.Error())
  378. }
  379. return nil
  380. }
  381. func deleteS3EnvGroup(config *config.Config, infra *models.Infra, lastApplied map[string]interface{}) error {
  382. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  383. if err != nil {
  384. return err
  385. }
  386. ooc := &kubernetes.OutOfClusterConfig{
  387. Repo: config.Repo,
  388. DigitalOceanOAuth: config.DOConf,
  389. Cluster: cluster,
  390. }
  391. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  392. if err != nil {
  393. return fmt.Errorf("failed to get agent: %s", err.Error())
  394. }
  395. err = envgroup.DeleteEnvGroup(agent, fmt.Sprintf("s3-credentials-%s", lastApplied["bucket_name"].(string)), "default")
  396. if err != nil {
  397. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  398. }
  399. return nil
  400. }