update_app.go 12 KB

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