update_app.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package porter_app
  2. import (
  3. "encoding/base64"
  4. "net/http"
  5. "connectrpc.com/connect"
  6. "github.com/porter-dev/api-contracts/generated/go/helpers"
  7. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  8. "github.com/porter-dev/porter/api/server/authz"
  9. "github.com/porter-dev/porter/api/server/handlers"
  10. "github.com/porter-dev/porter/api/server/shared"
  11. "github.com/porter-dev/porter/api/server/shared/apierrors"
  12. "github.com/porter-dev/porter/api/server/shared/config"
  13. "github.com/porter-dev/porter/api/types"
  14. "github.com/porter-dev/porter/internal/models"
  15. "github.com/porter-dev/porter/internal/porter_app"
  16. "github.com/porter-dev/porter/internal/telemetry"
  17. )
  18. // UpdateAppHandler is the handler for the POST /apps/update endpoint
  19. type UpdateAppHandler struct {
  20. handlers.PorterHandlerReadWriter
  21. authz.KubernetesAgentGetter
  22. }
  23. // NewUpdateAppHandler handles POST requests to the endpoint POST /apps/update
  24. func NewUpdateAppHandler(
  25. config *config.Config,
  26. decoderValidator shared.RequestDecoderValidator,
  27. writer shared.ResultWriter,
  28. ) *UpdateAppHandler {
  29. return &UpdateAppHandler{
  30. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  31. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  32. }
  33. }
  34. // UpdateAppRequest is the request object for the POST /apps/update endpoint
  35. type UpdateAppRequest struct {
  36. // Name is the name of the app to update. If not specified, the name will be inferred from the porter yaml
  37. Name string `json:"name"`
  38. // GitSource is the git source configuration for the app, if applicable
  39. GitSource GitSource `json:"git_source,omitempty"`
  40. // DeploymentTargetId is the ID of the deployment target to apply the update to
  41. DeploymentTargetId string `json:"deployment_target_id"`
  42. // Variables is a map of environment variable names to values
  43. Variables map[string]string `json:"variables"`
  44. // Secrets is a map of secret names to values
  45. Secrets map[string]string `json:"secrets"`
  46. // Deletions is the set of fields to delete before applying the update
  47. Deletions Deletions `json:"deletions"`
  48. // CommitSHA is the commit sha of the git commit that triggered this update, indicating a source change and triggering a build
  49. CommitSHA string `json:"commit_sha"`
  50. // PorterYAMLPath is the path to the porter yaml file in the git repo
  51. PorterYAMLPath string `json:"porter_yaml_path"`
  52. // AppRevisionID is the ID of the revision to perform follow up actions on after the initial apply
  53. AppRevisionID string `json:"app_revision_id"`
  54. // Only one of Base64AppProto or Base64PorterYAML should be specified
  55. // Base64AppProto is a ful base64 encoded porter app contract to apply
  56. Base64AppProto string `json:"b64_app_proto"`
  57. // Base64PorterYAML is a base64 encoded porter yaml to apply representing a potentially partial porter app contract
  58. Base64PorterYAML string `json:"b64_porter_yaml"`
  59. // IsEnvOverride is used to remove any variables that are not specified in the request. If false, the request will only update the variables specified in the request,
  60. // and leave all other variables untouched.
  61. IsEnvOverride bool `json:"is_env_override"`
  62. }
  63. // UpdateAppResponse is the response object for the POST /apps/update endpoint
  64. type UpdateAppResponse struct {
  65. AppName string `json:"app_name"`
  66. AppRevisionId string `json:"app_revision_id"`
  67. }
  68. // ServeHTTP translates the request into an UpdateApp request, forwards to the cluster control plane, and returns the response
  69. func (c *UpdateAppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  70. ctx, span := telemetry.NewSpan(r.Context(), "serve-update-app")
  71. defer span.End()
  72. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  73. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  74. request := &UpdateAppRequest{}
  75. if ok := c.DecodeAndValidate(w, r, request); !ok {
  76. err := telemetry.Error(ctx, span, nil, "error decoding request")
  77. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  78. return
  79. }
  80. if request.Base64AppProto != "" && request.Base64PorterYAML != "" {
  81. err := telemetry.Error(ctx, span, nil, "both b64 yaml and b64 porter yaml are specified")
  82. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  83. return
  84. }
  85. if request.DeploymentTargetId == "" {
  86. err := telemetry.Error(ctx, span, nil, "deployment target id is empty")
  87. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  88. return
  89. }
  90. deploymentTargetID := request.DeploymentTargetId
  91. telemetry.WithAttributes(span,
  92. telemetry.AttributeKV{Key: "name", Value: request.Name},
  93. telemetry.AttributeKV{Key: "deployment-target-id", Value: deploymentTargetID},
  94. telemetry.AttributeKV{Key: "app-revision-id", Value: request.AppRevisionID},
  95. telemetry.AttributeKV{Key: "commit-sha", Value: request.CommitSHA},
  96. telemetry.AttributeKV{Key: "porter-yaml-path", Value: request.PorterYAMLPath},
  97. telemetry.AttributeKV{Key: "is-env-override", Value: request.IsEnvOverride},
  98. )
  99. var overrides *porterv1.PorterApp
  100. appProto := &porterv1.PorterApp{}
  101. envVariables := request.Variables
  102. // get app definition from either base64 yaml or base64 porter app proto
  103. if request.Base64AppProto != "" {
  104. decoded, err := base64.StdEncoding.DecodeString(request.Base64AppProto)
  105. if err != nil {
  106. err := telemetry.Error(ctx, span, err, "error decoding base yaml")
  107. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  108. return
  109. }
  110. err = helpers.UnmarshalContractObject(decoded, appProto)
  111. if err != nil {
  112. err := telemetry.Error(ctx, span, err, "error unmarshalling app proto")
  113. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  114. return
  115. }
  116. }
  117. if request.Base64PorterYAML != "" {
  118. decoded, err := base64.StdEncoding.DecodeString(request.Base64PorterYAML)
  119. if err != nil {
  120. err := telemetry.Error(ctx, span, err, "error decoding base yaml")
  121. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  122. return
  123. }
  124. appFromYaml, err := porter_app.ParseYAML(ctx, decoded, request.Name)
  125. if err != nil {
  126. err := telemetry.Error(ctx, span, err, "error parsing yaml")
  127. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  128. return
  129. }
  130. appProto = appFromYaml.AppProto
  131. // only public variables can be defined in porter.yaml
  132. envVariables = mergeEnvVariables(request.Variables, appFromYaml.EnvVariables)
  133. if appFromYaml.PreviewApp != nil {
  134. overrides = appFromYaml.PreviewApp.AppProto
  135. envVariables = mergeEnvVariables(envVariables, appFromYaml.PreviewApp.EnvVariables)
  136. }
  137. }
  138. if appProto.Name == "" {
  139. if request.Name == "" {
  140. err := telemetry.Error(ctx, span, nil, "app name is empty")
  141. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  142. return
  143. }
  144. appProto.Name = request.Name
  145. }
  146. sourceType, image := sourceFromAppAndGitSource(appProto, request.GitSource)
  147. // create porter app if it doesn't exist for the given name
  148. _, err := porter_app.CreateOrGetAppRecord(ctx, porter_app.CreateOrGetAppRecordInput{
  149. ClusterID: cluster.ID,
  150. ProjectID: project.ID,
  151. Name: appProto.Name,
  152. SourceType: sourceType,
  153. GitBranch: request.GitSource.GitBranch,
  154. GitRepoName: request.GitSource.GitRepoName,
  155. GitRepoID: request.GitSource.GitRepoID,
  156. PorterYamlPath: request.PorterYAMLPath,
  157. Image: image,
  158. PorterAppRepository: c.Repo().PorterApp(),
  159. })
  160. if err != nil {
  161. err := telemetry.Error(ctx, span, err, "error creating or getting porter app")
  162. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  163. return
  164. }
  165. var serviceDeletions map[string]*porterv1.ServiceDeletions
  166. if request.Deletions.ServiceDeletions != nil {
  167. serviceDeletions = make(map[string]*porterv1.ServiceDeletions)
  168. for k, v := range request.Deletions.ServiceDeletions {
  169. serviceDeletions[k] = &porterv1.ServiceDeletions{
  170. DomainNames: v.DomainNames,
  171. IngressAnnotations: v.IngressAnnotationKeys,
  172. }
  173. }
  174. }
  175. updateReq := connect.NewRequest(&porterv1.UpdateAppRequest{
  176. ProjectId: int64(project.ID),
  177. DeploymentTargetIdentifier: &porterv1.DeploymentTargetIdentifier{
  178. Id: deploymentTargetID,
  179. },
  180. App: appProto,
  181. AppRevisionId: request.AppRevisionID,
  182. AppEnv: &porterv1.EnvGroupVariables{
  183. Normal: envVariables,
  184. Secret: request.Secrets,
  185. },
  186. Deletions: &porterv1.Deletions{
  187. ServiceNames: request.Deletions.ServiceNames,
  188. PredeployNames: request.Deletions.Predeploy,
  189. EnvVariableNames: request.Deletions.EnvVariableNames,
  190. EnvGroupNames: request.Deletions.EnvGroupNames,
  191. ServiceDeletions: serviceDeletions,
  192. },
  193. AppOverrides: overrides,
  194. CommitSha: request.CommitSHA,
  195. IsEnvOverride: request.IsEnvOverride,
  196. })
  197. ccpResp, err := c.Config().ClusterControlPlaneClient.UpdateApp(ctx, updateReq)
  198. if err != nil {
  199. err := telemetry.Error(ctx, span, err, "error calling ccp update app")
  200. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  201. return
  202. }
  203. if ccpResp == nil {
  204. err := telemetry.Error(ctx, span, err, "ccp resp is nil")
  205. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  206. return
  207. }
  208. if ccpResp.Msg == nil {
  209. err := telemetry.Error(ctx, span, err, "ccp resp msg is nil")
  210. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  211. return
  212. }
  213. if ccpResp.Msg.AppRevisionId == "" {
  214. err := telemetry.Error(ctx, span, err, "ccp resp app revision id is empty")
  215. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  216. return
  217. }
  218. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "resp-app-revision-id", Value: ccpResp.Msg.AppRevisionId})
  219. response := &UpdateAppResponse{
  220. AppRevisionId: ccpResp.Msg.AppRevisionId,
  221. AppName: appProto.Name,
  222. }
  223. c.WriteResult(w, r, response)
  224. }
  225. func sourceFromAppAndGitSource(appProto *porterv1.PorterApp, gitSource GitSource) (porter_app.SourceType, *porter_app.Image) {
  226. var sourceType porter_app.SourceType
  227. var image *porter_app.Image
  228. if appProto.Build != nil {
  229. if gitSource.GitRepoID == 0 {
  230. return porter_app.SourceType_Local, nil
  231. }
  232. sourceType = porter_app.SourceType_Github
  233. }
  234. if appProto.Image != nil {
  235. sourceType = porter_app.SourceType_DockerRegistry
  236. image = &porter_app.Image{
  237. Repository: appProto.Image.Repository,
  238. Tag: appProto.Image.Tag,
  239. }
  240. }
  241. return sourceType, image
  242. }
  243. func mergeEnvVariables(currentEnv, previousEnv map[string]string) map[string]string {
  244. env := make(map[string]string)
  245. for k, v := range previousEnv {
  246. env[k] = v
  247. }
  248. for k, v := range currentEnv {
  249. env[k] = v
  250. }
  251. return env
  252. }