2
0

create_resource.go 15 KB

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