create_resource.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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):
  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.InfraDOCR):
  88. _, err = createDOCRRegistry(c.Config, infra, operation, req.Output)
  89. case string(types.InfraGCR):
  90. _, err = createGCRRegistry(c.Config, infra, operation, req.Output)
  91. }
  92. if err != nil {
  93. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  94. return
  95. }
  96. }
  97. func createECRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  98. reg := &models.Registry{
  99. ProjectID: infra.ProjectID,
  100. AWSIntegrationID: infra.AWSIntegrationID,
  101. InfraID: infra.ID,
  102. Name: output["name"].(string),
  103. }
  104. // parse raw data into ECR type
  105. awsInt, err := config.Repo.AWSIntegration().ReadAWSIntegration(reg.ProjectID, reg.AWSIntegrationID)
  106. if err != nil {
  107. return nil, err
  108. }
  109. sess, err := awsInt.GetSession()
  110. if err != nil {
  111. return nil, err
  112. }
  113. ecrSvc := ecr.New(sess)
  114. authOutput, err := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{})
  115. if err != nil {
  116. return nil, err
  117. }
  118. reg.URL = *authOutput.AuthorizationData[0].ProxyEndpoint
  119. reg, err = config.Repo.Registry().CreateRegistry(reg)
  120. if err != nil {
  121. return nil, err
  122. }
  123. return reg, nil
  124. }
  125. func createRDSDatabase(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Database, error) {
  126. // check for infra id being 0 as a safeguard so that all non-provisioned
  127. // clusters are not matched by read
  128. if infra.ID == 0 {
  129. return nil, fmt.Errorf("infra id cannot be 0")
  130. }
  131. var database *models.Database
  132. var err error
  133. var isNotFound bool
  134. database, err = config.Repo.Database().ReadDatabaseByInfraID(infra.ProjectID, infra.ID)
  135. isNotFound = err != nil && errors.Is(err, gorm.ErrRecordNotFound)
  136. if isNotFound {
  137. database = &models.Database{
  138. ProjectID: infra.ProjectID,
  139. ClusterID: infra.ParentClusterID,
  140. InfraID: infra.ID,
  141. Status: "Running",
  142. }
  143. } else if err != nil {
  144. return nil, err
  145. }
  146. database.InstanceID = output["rds_instance_id"].(string)
  147. database.InstanceEndpoint = output["rds_connection_endpoint"].(string)
  148. database.InstanceName = output["rds_instance_name"].(string)
  149. if isNotFound {
  150. database, err = config.Repo.Database().CreateDatabase(database)
  151. } else {
  152. database, err = config.Repo.Database().UpdateDatabase(database)
  153. }
  154. infra.DatabaseID = database.ID
  155. infra, err = config.Repo.Infra().UpdateInfra(infra)
  156. if err != nil {
  157. return nil, err
  158. }
  159. lastApplied := make(map[string]interface{})
  160. err = json.Unmarshal(operation.LastApplied, &lastApplied)
  161. if err != nil {
  162. return nil, err
  163. }
  164. err = createRDSEnvGroup(config, infra, database, lastApplied)
  165. if err != nil {
  166. return nil, err
  167. }
  168. return database, nil
  169. }
  170. func createCluster(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Cluster, error) {
  171. // check for infra id being 0 as a safeguard so that all non-provisioned
  172. // clusters are not matched by read
  173. if infra.ID == 0 {
  174. return nil, fmt.Errorf("infra id cannot be 0")
  175. }
  176. var cluster *models.Cluster
  177. var err error
  178. var isNotFound bool
  179. // look for cluster matching infra in database; if the cluster already exists, update the cluster but
  180. // don't add it again
  181. cluster, err = config.Repo.Cluster().ReadClusterByInfraID(infra.ProjectID, infra.ID)
  182. isNotFound = err != nil && errors.Is(err, gorm.ErrRecordNotFound)
  183. if isNotFound {
  184. cluster = getNewCluster(infra)
  185. } else if err != nil {
  186. return nil, err
  187. }
  188. caData, err := transformClusterCAData([]byte(output["cluster_ca_data"].(string)))
  189. if err != nil {
  190. return nil, err
  191. }
  192. cluster.Name = output["cluster_name"].(string)
  193. cluster.Server = output["cluster_endpoint"].(string)
  194. cluster.CertificateAuthorityData = caData
  195. if isNotFound {
  196. cluster, err = config.Repo.Cluster().CreateCluster(cluster)
  197. } else {
  198. cluster, err = config.Repo.Cluster().UpdateCluster(cluster)
  199. }
  200. if err != nil {
  201. return nil, err
  202. }
  203. return cluster, nil
  204. }
  205. func getNewCluster(infra *models.Infra) *models.Cluster {
  206. res := &models.Cluster{
  207. ProjectID: infra.ProjectID,
  208. InfraID: infra.ID,
  209. }
  210. switch infra.Kind {
  211. case types.InfraEKS:
  212. res.AuthMechanism = models.AWS
  213. res.AWSIntegrationID = infra.AWSIntegrationID
  214. case types.InfraGKE:
  215. res.AuthMechanism = models.GCP
  216. res.GCPIntegrationID = infra.GCPIntegrationID
  217. case types.InfraDOKS:
  218. res.AuthMechanism = models.DO
  219. res.DOIntegrationID = infra.DOIntegrationID
  220. }
  221. return res
  222. }
  223. func transformClusterCAData(ca []byte) ([]byte, error) {
  224. re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
  225. // if it matches the base64 regex, decode it
  226. caData := string(ca)
  227. if re.MatchString(caData) {
  228. decoded, err := base64.StdEncoding.DecodeString(caData)
  229. if err != nil {
  230. return nil, err
  231. }
  232. return []byte(decoded), nil
  233. }
  234. // otherwise just return the CA
  235. return ca, nil
  236. }
  237. func createDOCRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  238. reg := &models.Registry{
  239. ProjectID: infra.ProjectID,
  240. DOIntegrationID: infra.DOIntegrationID,
  241. InfraID: infra.ID,
  242. URL: output["url"].(string),
  243. Name: output["name"].(string),
  244. }
  245. return config.Repo.Registry().CreateRegistry(reg)
  246. }
  247. func createGCRRegistry(config *config.Config, infra *models.Infra, operation *models.Operation, output map[string]interface{}) (*models.Registry, error) {
  248. reg := &models.Registry{
  249. ProjectID: infra.ProjectID,
  250. GCPIntegrationID: infra.GCPIntegrationID,
  251. InfraID: infra.ID,
  252. URL: output["url"].(string),
  253. Name: "gcr-registry",
  254. }
  255. return config.Repo.Registry().CreateRegistry(reg)
  256. }
  257. func createRDSEnvGroup(config *config.Config, infra *models.Infra, database *models.Database, lastApplied map[string]interface{}) error {
  258. cluster, err := config.Repo.Cluster().ReadCluster(infra.ProjectID, infra.ParentClusterID)
  259. if err != nil {
  260. return err
  261. }
  262. ooc := &kubernetes.OutOfClusterConfig{
  263. Repo: config.Repo,
  264. DigitalOceanOAuth: config.DOConf,
  265. Cluster: cluster,
  266. }
  267. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  268. if err != nil {
  269. return fmt.Errorf("failed to get agent: %s", err.Error())
  270. }
  271. // split the instance endpoint on the port
  272. port := "5432"
  273. host := database.InstanceEndpoint
  274. if strArr := strings.Split(database.InstanceEndpoint, ":"); len(strArr) == 2 {
  275. host = strArr[0]
  276. port = strArr[1]
  277. }
  278. _, err = envgroup.CreateEnvGroup(agent, types.ConfigMapInput{
  279. Name: fmt.Sprintf("rds-credentials-%s", lastApplied["db_name"].(string)),
  280. Namespace: "default",
  281. Variables: map[string]string{},
  282. SecretVariables: map[string]string{
  283. "PGPORT": port,
  284. "PGHOST": host,
  285. "PGPASSWORD": lastApplied["db_passwd"].(string),
  286. "PGUSER": lastApplied["db_user"].(string),
  287. },
  288. })
  289. if err != nil {
  290. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  291. }
  292. return nil
  293. }
  294. func deleteRDSEnvGroup(config *config.Config, infra *models.Infra, 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. err = envgroup.DeleteEnvGroup(agent, fmt.Sprintf("rds-credentials-%s", lastApplied["db_name"].(string)), "default")
  309. if err != nil {
  310. return fmt.Errorf("failed to create RDS env group: %s", err.Error())
  311. }
  312. return nil
  313. }