apply.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. package porter_app
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "connectrpc.com/connect"
  9. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  10. "github.com/porter-dev/api-contracts/generated/go/helpers"
  11. "github.com/porter-dev/porter/internal/deployment_target"
  12. "github.com/porter-dev/porter/internal/porter_app"
  13. "github.com/porter-dev/porter/internal/telemetry"
  14. "github.com/porter-dev/porter/api/server/authz"
  15. "github.com/porter-dev/porter/api/server/handlers"
  16. "github.com/porter-dev/porter/api/server/shared"
  17. "github.com/porter-dev/porter/api/server/shared/apierrors"
  18. "github.com/porter-dev/porter/api/server/shared/config"
  19. "github.com/porter-dev/porter/api/types"
  20. "github.com/porter-dev/porter/internal/models"
  21. )
  22. // ApplyPorterAppHandler is the handler for the /apps/parse endpoint
  23. type ApplyPorterAppHandler struct {
  24. handlers.PorterHandlerReadWriter
  25. authz.KubernetesAgentGetter
  26. }
  27. // NewApplyPorterAppHandler handles POST requests to the endpoint /apps/apply
  28. func NewApplyPorterAppHandler(
  29. config *config.Config,
  30. decoderValidator shared.RequestDecoderValidator,
  31. writer shared.ResultWriter,
  32. ) *ApplyPorterAppHandler {
  33. return &ApplyPorterAppHandler{
  34. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  35. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  36. }
  37. }
  38. // ApplyPorterAppRequest is the request object for the /apps/apply endpoint
  39. type ApplyPorterAppRequest struct {
  40. Base64AppProto string `json:"b64_app_proto"`
  41. DeploymentTargetId string `json:"deployment_target_id"`
  42. AppRevisionID string `json:"app_revision_id"`
  43. ForceBuild bool `json:"force_build"`
  44. }
  45. // ApplyPorterAppResponse is the response object for the /apps/apply endpoint
  46. type ApplyPorterAppResponse struct {
  47. AppRevisionId string `json:"app_revision_id"`
  48. CLIAction porterv1.EnumCLIAction `json:"cli_action"`
  49. }
  50. // ServeHTTP translates the request into a ApplyPorterApp request, forwards to the cluster control plane, and returns the response
  51. func (c *ApplyPorterAppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  52. ctx, span := telemetry.NewSpan(r.Context(), "serve-apply-porter-app")
  53. defer span.End()
  54. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  55. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  56. telemetry.WithAttributes(span,
  57. telemetry.AttributeKV{Key: "project-id", Value: project.ID},
  58. telemetry.AttributeKV{Key: "cluster-id", Value: cluster.ID},
  59. )
  60. if !project.GetFeatureFlag(models.ValidateApplyV2, c.Config().LaunchDarklyClient) {
  61. err := telemetry.Error(ctx, span, nil, "project does not have validate apply v2 enabled")
  62. c.HandleAPIError(w, r, apierrors.NewErrForbidden(err))
  63. return
  64. }
  65. request := &ApplyPorterAppRequest{}
  66. if ok := c.DecodeAndValidate(w, r, request); !ok {
  67. err := telemetry.Error(ctx, span, nil, "error decoding request")
  68. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  69. return
  70. }
  71. var appRevisionID string
  72. var appProto *porterv1.PorterApp
  73. var deploymentTargetID string
  74. if request.AppRevisionID != "" {
  75. appRevisionID = request.AppRevisionID
  76. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "app-revision-id", Value: request.AppRevisionID})
  77. } else {
  78. if request.Base64AppProto == "" {
  79. err := telemetry.Error(ctx, span, nil, "b64 yaml is empty")
  80. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  81. return
  82. }
  83. decoded, err := base64.StdEncoding.DecodeString(request.Base64AppProto)
  84. if err != nil {
  85. err := telemetry.Error(ctx, span, err, "error decoding base yaml")
  86. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  87. return
  88. }
  89. appProto = &porterv1.PorterApp{}
  90. err = helpers.UnmarshalContractObject(decoded, appProto)
  91. if err != nil {
  92. err := telemetry.Error(ctx, span, err, "error unmarshalling app proto")
  93. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  94. return
  95. }
  96. if request.DeploymentTargetId == "" {
  97. err := telemetry.Error(ctx, span, err, "deployment target id is empty")
  98. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  99. return
  100. }
  101. deploymentTargetID = request.DeploymentTargetId
  102. telemetry.WithAttributes(span,
  103. telemetry.AttributeKV{Key: "app-name", Value: appProto.Name},
  104. telemetry.AttributeKV{Key: "deployment-target-id", Value: request.DeploymentTargetId},
  105. )
  106. deploymentTargetDetails, err := deployment_target.DeploymentTargetDetails(ctx, deployment_target.DeploymentTargetDetailsInput{
  107. ProjectID: int64(project.ID),
  108. ClusterID: int64(cluster.ID),
  109. DeploymentTargetID: deploymentTargetID,
  110. CCPClient: c.Config().ClusterControlPlaneClient,
  111. })
  112. if err != nil {
  113. err := telemetry.Error(ctx, span, err, "error getting deployment target details")
  114. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  115. return
  116. }
  117. agent, err := c.GetAgent(r, cluster, "")
  118. if err != nil {
  119. err := telemetry.Error(ctx, span, err, "error getting kubernetes agent")
  120. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  121. return
  122. }
  123. subdomainCreateInput := porter_app.CreatePorterSubdomainInput{
  124. AppName: appProto.Name,
  125. RootDomain: c.Config().ServerConf.AppRootDomain,
  126. DNSClient: c.Config().DNSClient,
  127. DNSRecordRepository: c.Repo().DNSRecord(),
  128. KubernetesAgent: agent,
  129. }
  130. appProto, err = addPorterSubdomainsIfNecessary(ctx, appProto, deploymentTargetDetails, subdomainCreateInput)
  131. if err != nil {
  132. err := telemetry.Error(ctx, span, err, "error adding porter subdomains")
  133. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  134. return
  135. }
  136. }
  137. applyReq := connect.NewRequest(&porterv1.ApplyPorterAppRequest{
  138. ProjectId: int64(project.ID),
  139. DeploymentTargetId: deploymentTargetID,
  140. App: appProto,
  141. PorterAppRevisionId: appRevisionID,
  142. ForceBuild: request.ForceBuild,
  143. })
  144. ccpResp, err := c.Config().ClusterControlPlaneClient.ApplyPorterApp(ctx, applyReq)
  145. if err != nil {
  146. err := telemetry.Error(ctx, span, err, "error calling ccp apply porter app")
  147. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  148. return
  149. }
  150. if ccpResp == nil {
  151. err := telemetry.Error(ctx, span, err, "ccp resp is nil")
  152. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  153. return
  154. }
  155. if ccpResp.Msg == nil {
  156. err := telemetry.Error(ctx, span, err, "ccp resp msg is nil")
  157. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  158. return
  159. }
  160. if ccpResp.Msg.PorterAppRevisionId == "" {
  161. err := telemetry.Error(ctx, span, err, "ccp resp app revision id is nil")
  162. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  163. return
  164. }
  165. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "resp-app-revision-id", Value: ccpResp.Msg.PorterAppRevisionId})
  166. if ccpResp.Msg.CliAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_UNSPECIFIED {
  167. err := telemetry.Error(ctx, span, err, "ccp resp cli action is nil")
  168. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  169. return
  170. }
  171. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "cli-action", Value: ccpResp.Msg.CliAction.String()})
  172. response := &ApplyPorterAppResponse{
  173. AppRevisionId: ccpResp.Msg.PorterAppRevisionId,
  174. CLIAction: ccpResp.Msg.CliAction,
  175. }
  176. c.WriteResult(w, r, response)
  177. }
  178. // addPorterSubdomainsIfNecessary adds porter subdomains to the app proto if a web service is changed to private and has no domains
  179. func addPorterSubdomainsIfNecessary(ctx context.Context, app *porterv1.PorterApp, deploymentTarget deployment_target.DeploymentTarget, createSubdomainInput porter_app.CreatePorterSubdomainInput) (*porterv1.PorterApp, error) {
  180. for serviceName, service := range app.Services {
  181. if service.Type == porterv1.ServiceType_SERVICE_TYPE_WEB {
  182. if service.GetWebConfig() == nil {
  183. return app, fmt.Errorf("web service %s does not contain web config", serviceName)
  184. }
  185. webConfig := service.GetWebConfig()
  186. if !webConfig.GetPrivate() && len(webConfig.Domains) == 0 {
  187. if deploymentTarget.Namespace != DeploymentTargetSelector_Default {
  188. createSubdomainInput.AppName = fmt.Sprintf("%s-%s", createSubdomainInput.AppName, deploymentTarget.Namespace)
  189. }
  190. subdomain, err := porter_app.CreatePorterSubdomain(ctx, createSubdomainInput)
  191. if err != nil {
  192. return app, fmt.Errorf("error creating subdomain: %w", err)
  193. }
  194. if subdomain == "" {
  195. return app, errors.New("response subdomain is empty")
  196. }
  197. webConfig.Domains = []*porterv1.Domain{
  198. {Name: subdomain},
  199. }
  200. service.Config = &porterv1.Service_WebConfig{WebConfig: webConfig}
  201. }
  202. }
  203. }
  204. return app, nil
  205. }