create_addon.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. package release
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "connectrpc.com/connect"
  8. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  9. "github.com/porter-dev/porter/api/server/authz"
  10. "github.com/porter-dev/porter/api/server/handlers"
  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/server/shared/config"
  14. "github.com/porter-dev/porter/api/types"
  15. "github.com/porter-dev/porter/internal/analytics"
  16. "github.com/porter-dev/porter/internal/helm"
  17. "github.com/porter-dev/porter/internal/helm/loader"
  18. "github.com/porter-dev/porter/internal/kubernetes"
  19. "github.com/porter-dev/porter/internal/models"
  20. "github.com/porter-dev/porter/internal/oauth"
  21. "github.com/porter-dev/porter/internal/telemetry"
  22. "github.com/stefanmcshane/helm/pkg/chart"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. )
  25. // Namespace_EnvironmentGroups is the base namespace for storing all environment groups.
  26. const Namespace_EnvironmentGroups = "porter-env-group"
  27. // Namespace_ACKSystem is the base namespace for interacting with ack chart controllers
  28. const Namespace_ACKSystem = "ack-system"
  29. type CreateAddonHandler struct {
  30. handlers.PorterHandlerReadWriter
  31. authz.KubernetesAgentGetter
  32. }
  33. func NewCreateAddonHandler(
  34. config *config.Config,
  35. decoderValidator shared.RequestDecoderValidator,
  36. writer shared.ResultWriter,
  37. ) *CreateAddonHandler {
  38. return &CreateAddonHandler{
  39. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  40. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  41. }
  42. }
  43. func (c *CreateAddonHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  44. ctx, span := telemetry.NewSpan(r.Context(), "serve-create-addon")
  45. defer span.End()
  46. user, _ := ctx.Value(types.UserScope).(*models.User)
  47. proj, _ := ctx.Value(types.ProjectScope).(*models.Project)
  48. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  49. namespace := ctx.Value(types.NamespaceScope).(string)
  50. operationID := oauth.CreateRandomState()
  51. c.Config().AnalyticsClient.Track(analytics.ApplicationLaunchStartTrack(
  52. &analytics.ApplicationLaunchStartTrackOpts{
  53. ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(user.ID, cluster.ProjectID, cluster.ID),
  54. FlowID: operationID,
  55. },
  56. ))
  57. helmAgent, err := c.GetHelmAgent(ctx, r, cluster, "")
  58. if err != nil {
  59. err = telemetry.Error(ctx, span, nil, "error creating helm agent")
  60. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  61. return
  62. }
  63. request := &types.CreateAddonRequest{}
  64. if ok := c.DecodeAndValidate(w, r, request); !ok {
  65. err := telemetry.Error(ctx, span, nil, "error decoding request")
  66. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  67. return
  68. }
  69. if request.TemplateVersion == "latest" {
  70. request.TemplateVersion = ""
  71. }
  72. telemetry.WithAttributes(span,
  73. telemetry.AttributeKV{Key: "repo-url", Value: request.RepoURL},
  74. telemetry.AttributeKV{Key: "template-name", Value: request.TemplateName},
  75. telemetry.AttributeKV{Key: "template-version", Value: request.TemplateVersion},
  76. )
  77. chart, err := LoadChart(ctx, c.Config(), &LoadAddonChartOpts{
  78. ProjectID: proj.ID,
  79. RepoURL: request.RepoURL,
  80. TemplateName: request.TemplateName,
  81. TemplateVersion: request.TemplateVersion,
  82. })
  83. if err != nil {
  84. err = telemetry.Error(ctx, span, nil, "error loading chart")
  85. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  86. return
  87. }
  88. registries, err := c.Repo().Registry().ListRegistriesByProjectID(cluster.ProjectID)
  89. if err != nil {
  90. err = telemetry.Error(ctx, span, err, "error retrieving project registry")
  91. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  92. return
  93. }
  94. vpcConfig, err := c.getVPCConfig(ctx, request, proj, cluster)
  95. if err != nil {
  96. err = telemetry.Error(ctx, span, err, "error retrieving vpc config")
  97. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  98. return
  99. }
  100. if err := c.performAddonPreinstall(ctx, r, request.TemplateName, cluster); err != nil {
  101. err = telemetry.Error(ctx, span, err, "error performing addon preinstall")
  102. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  103. return
  104. }
  105. values := request.Values
  106. values["vpcConfig"] = vpcConfig
  107. conf := &helm.InstallChartConfig{
  108. Chart: chart,
  109. Name: request.Name,
  110. Namespace: namespace,
  111. Values: values,
  112. Cluster: cluster,
  113. Repo: c.Repo(),
  114. Registries: registries,
  115. }
  116. helmRelease, err := helmAgent.InstallChart(ctx, conf, c.Config().DOConf, c.Config().ServerConf.DisablePullSecretsInjection)
  117. if err != nil {
  118. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  119. telemetry.Error(ctx, span, nil, fmt.Sprintf("error installing a new chart: %s", err.Error())),
  120. http.StatusBadRequest,
  121. ))
  122. return
  123. }
  124. c.Config().AnalyticsClient.Track(analytics.ApplicationLaunchSuccessTrack(
  125. &analytics.ApplicationLaunchSuccessTrackOpts{
  126. ApplicationScopedTrackOpts: analytics.GetApplicationScopedTrackOpts(
  127. user.ID,
  128. cluster.ProjectID,
  129. cluster.ID,
  130. helmRelease.Name,
  131. helmRelease.Namespace,
  132. chart.Metadata.Name,
  133. ),
  134. FlowID: operationID,
  135. },
  136. ))
  137. }
  138. type LoadAddonChartOpts struct {
  139. ProjectID uint
  140. RepoURL, TemplateName, TemplateVersion string
  141. }
  142. // LoadChart fetches a chart from a remote repo
  143. func LoadChart(ctx context.Context, config *config.Config, opts *LoadAddonChartOpts) (*chart.Chart, error) {
  144. // if the chart repo url is one of the specified application/addon charts, just load public
  145. if opts.RepoURL == config.ServerConf.DefaultAddonHelmRepoURL || opts.RepoURL == config.ServerConf.DefaultApplicationHelmRepoURL {
  146. return loader.LoadChartPublic(ctx, opts.RepoURL, opts.TemplateName, opts.TemplateVersion)
  147. } else {
  148. // load the helm repos in the project
  149. hrs, err := config.Repo.HelmRepo().ListHelmReposByProjectID(opts.ProjectID)
  150. if err != nil {
  151. return nil, err
  152. }
  153. for _, hr := range hrs {
  154. if hr.RepoURL == opts.RepoURL {
  155. if hr.BasicAuthIntegrationID != 0 {
  156. // read the basic integration id
  157. basic, err := config.Repo.BasicIntegration().ReadBasicIntegration(opts.ProjectID, hr.BasicAuthIntegrationID)
  158. if err != nil {
  159. return nil, err
  160. }
  161. return loader.LoadChart(ctx,
  162. &loader.BasicAuthClient{
  163. Username: string(basic.Username),
  164. Password: string(basic.Password),
  165. }, hr.RepoURL, opts.TemplateName, opts.TemplateVersion)
  166. } else {
  167. return loader.LoadChartPublic(ctx, hr.RepoURL, opts.TemplateName, opts.TemplateVersion)
  168. }
  169. }
  170. }
  171. }
  172. return nil, fmt.Errorf("chart repo not found")
  173. }
  174. func (c *CreateAddonHandler) performAddonPreinstall(ctx context.Context, r *http.Request, templateName string, cluster *models.Cluster) error {
  175. ctx, span := telemetry.NewSpan(ctx, "addon-preinstall")
  176. defer span.End()
  177. awsTemplates := map[string][]string{
  178. "elasticache-redis": {"ack-chart-ec2", "ack-chart-elasticache"},
  179. "rds-postgresql": {"ack-chart-ec2", "ack-chart-rds"},
  180. "rds-postgresql-aurora": {"ack-chart-ec2", "ack-chart-rds"},
  181. }
  182. telemetry.WithAttributes(span,
  183. telemetry.AttributeKV{Key: "template-name", Value: templateName},
  184. telemetry.AttributeKV{Key: "cloud-provider", Value: cluster.CloudProvider},
  185. )
  186. if cluster.CloudProvider != "AWS" {
  187. return nil
  188. }
  189. if _, ok := awsTemplates[templateName]; !ok {
  190. return nil
  191. }
  192. agent, err := c.GetAgent(r, cluster, "")
  193. if err != nil {
  194. return telemetry.Error(ctx, span, err, "failed to get k8s agent")
  195. }
  196. if _, err = agent.GetNamespace(Namespace_EnvironmentGroups); err != nil {
  197. if _, err := agent.CreateNamespace(Namespace_EnvironmentGroups, map[string]string{}); err != nil {
  198. return telemetry.Error(ctx, span, err, "failed creating porter-env-group namespace")
  199. }
  200. }
  201. for _, chart := range awsTemplates[templateName] {
  202. if err := c.scaleAckChartDeployment(ctx, chart, agent); err != nil {
  203. return telemetry.Error(ctx, span, err, "failed scaling ack chart deployment")
  204. }
  205. }
  206. return nil
  207. }
  208. func (c *CreateAddonHandler) scaleAckChartDeployment(ctx context.Context, chart string, agent *kubernetes.Agent) error {
  209. ctx, span := telemetry.NewSpan(ctx, "scale-ack-chart")
  210. defer span.End()
  211. telemetry.WithAttributes(span,
  212. telemetry.AttributeKV{Key: "namespace", Value: Namespace_ACKSystem},
  213. telemetry.AttributeKV{Key: "chart-name", Value: chart},
  214. )
  215. scale, err := agent.Clientset.AppsV1().Deployments(Namespace_ACKSystem).GetScale(ctx, chart, metav1.GetOptions{})
  216. if err != nil {
  217. return telemetry.Error(ctx, span, err, "failed getting deployment")
  218. }
  219. if scale.Spec.Replicas > 0 {
  220. return nil
  221. }
  222. scale.Spec.Replicas = 1
  223. if _, err := agent.Clientset.AppsV1().Deployments(Namespace_ACKSystem).UpdateScale(ctx, chart, scale, metav1.UpdateOptions{}); err != nil {
  224. return telemetry.Error(ctx, span, err, "failed scaling deployment up")
  225. }
  226. return nil
  227. }
  228. func (c *CreateAddonHandler) getVPCConfig(ctx context.Context, request *types.CreateAddonRequest, project *models.Project, cluster *models.Cluster) (map[string]any, error) {
  229. ctx, span := telemetry.NewSpan(ctx, "get-vpc-config")
  230. defer span.End()
  231. telemetry.WithAttributes(span,
  232. telemetry.AttributeKV{Key: "cloud-provider", Value: cluster.CloudProvider},
  233. telemetry.AttributeKV{Key: "template-name", Value: request.TemplateName},
  234. )
  235. vpcConfig := map[string]any{}
  236. if cluster.CloudProvider != "AWS" {
  237. return vpcConfig, nil
  238. }
  239. awsTemplates := map[string]string{
  240. "elasticache-redis": "elasticache",
  241. "rds-postgresql": "rds",
  242. "rds-postgresql-aurora": "rds",
  243. }
  244. serviceType, ok := awsTemplates[request.TemplateName]
  245. if !ok {
  246. return vpcConfig, nil
  247. }
  248. req := connect.NewRequest(&porterv1.SharedNetworkSettingsRequest{
  249. ProjectId: int64(project.ID),
  250. ClusterId: int64(cluster.ID),
  251. ServiceType: serviceType,
  252. })
  253. resp, err := c.Config().ClusterControlPlaneClient.SharedNetworkSettings(ctx, req)
  254. if err != nil {
  255. return vpcConfig, telemetry.Error(ctx, span, err, "error fetching cluster network settings from ccp")
  256. }
  257. vpcConfig["cidrBlock"] = resp.Msg.CidrRange
  258. vpcConfig["subnetIDs"] = resp.Msg.SubnetIds
  259. switch resp.Msg.CloudProvider {
  260. case *porterv1.EnumCloudProvider_ENUM_CLOUD_PROVIDER_AWS.Enum():
  261. vpcConfig["awsRegion"] = resp.Msg.Region
  262. vpcConfig["vpcID"] = resp.Msg.GetEksCloudProviderNetwork().Id
  263. telemetry.WithAttributes(span,
  264. telemetry.AttributeKV{Key: "aws-region", Value: resp.Msg.Region},
  265. telemetry.AttributeKV{Key: "vpc-id", Value: resp.Msg.GetEksCloudProviderNetwork().Id},
  266. )
  267. }
  268. telemetry.WithAttributes(span,
  269. telemetry.AttributeKV{Key: "cidr-block", Value: resp.Msg.CidrRange},
  270. telemetry.AttributeKV{Key: "subnet-ids", Value: strings.Join(resp.Msg.SubnetIds, ",")},
  271. )
  272. return vpcConfig, nil
  273. }