apply.go 9.4 KB

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