update_app.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. // ImageTagOverride is the image tag to override the image tag in the porter.yaml (it will override the image tag in the porter.yaml if specified)
  52. ImageTagOverride string `json:"image_tag_override"`
  53. // PorterYAMLPath is the path to the porter yaml file in the git repo
  54. PorterYAMLPath string `json:"porter_yaml_path"`
  55. // AppRevisionID is the ID of the revision to perform follow up actions on after the initial apply
  56. AppRevisionID string `json:"app_revision_id"`
  57. // Only one of Base64AppProto or Base64PorterYAML should be specified
  58. // Base64AppProto is a ful base64 encoded porter app contract to apply
  59. Base64AppProto string `json:"b64_app_proto"`
  60. // Base64AddonProtos is a list of base64 encoded addon contracts to apply along with the app
  61. Base64AddonProtos []string `json:"b64_addon_protos"`
  62. // Base64PorterYAML is a base64 encoded porter yaml to apply representing a potentially partial porter app contract
  63. Base64PorterYAML string `json:"b64_porter_yaml"`
  64. // 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,
  65. // and leave all other variables untouched.
  66. IsEnvOverride bool `json:"is_env_override"`
  67. }
  68. // UpdateAppResponse is the response object for the POST /apps/update endpoint
  69. type UpdateAppResponse struct {
  70. AppName string `json:"app_name"`
  71. AppRevisionId string `json:"app_revision_id"`
  72. }
  73. // ServeHTTP translates the request into an UpdateApp request, forwards to the cluster control plane, and returns the response
  74. func (c *UpdateAppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  75. ctx, span := telemetry.NewSpan(r.Context(), "serve-update-app")
  76. defer span.End()
  77. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  78. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  79. request := &UpdateAppRequest{}
  80. if ok := c.DecodeAndValidate(w, r, request); !ok {
  81. err := telemetry.Error(ctx, span, nil, "error decoding request")
  82. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  83. return
  84. }
  85. if request.Base64AppProto != "" && request.Base64PorterYAML != "" {
  86. err := telemetry.Error(ctx, span, nil, "both b64 yaml and b64 porter yaml are specified")
  87. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  88. return
  89. }
  90. if request.DeploymentTargetId == "" {
  91. err := telemetry.Error(ctx, span, nil, "deployment target id is empty")
  92. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  93. return
  94. }
  95. deploymentTargetID := request.DeploymentTargetId
  96. telemetry.WithAttributes(span,
  97. telemetry.AttributeKV{Key: "name", Value: request.Name},
  98. telemetry.AttributeKV{Key: "deployment-target-id", Value: deploymentTargetID},
  99. telemetry.AttributeKV{Key: "app-revision-id", Value: request.AppRevisionID},
  100. telemetry.AttributeKV{Key: "commit-sha", Value: request.CommitSHA},
  101. telemetry.AttributeKV{Key: "porter-yaml-path", Value: request.PorterYAMLPath},
  102. telemetry.AttributeKV{Key: "is-env-override", Value: request.IsEnvOverride},
  103. )
  104. var addons, addonOverrides []*porterv1.Addon
  105. var overrides *porterv1.PorterApp
  106. appProto := &porterv1.PorterApp{}
  107. envVariables := request.Variables
  108. // get app definition from either base64 yaml or base64 porter app proto
  109. if request.Base64AppProto != "" {
  110. decoded, err := base64.StdEncoding.DecodeString(request.Base64AppProto)
  111. if err != nil {
  112. err := telemetry.Error(ctx, span, err, "error decoding base yaml")
  113. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  114. return
  115. }
  116. err = helpers.UnmarshalContractObject(decoded, appProto)
  117. if err != nil {
  118. err := telemetry.Error(ctx, span, err, "error unmarshalling app proto")
  119. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  120. return
  121. }
  122. }
  123. for _, b64AddonProto := range request.Base64AddonProtos {
  124. decoded, err := base64.StdEncoding.DecodeString(b64AddonProto)
  125. if err != nil {
  126. err := telemetry.Error(ctx, span, err, "error decoding base yaml")
  127. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  128. return
  129. }
  130. addon := &porterv1.Addon{}
  131. err = helpers.UnmarshalContractObject(decoded, addon)
  132. if err != nil {
  133. err := telemetry.Error(ctx, span, err, "error unmarshalling addon proto")
  134. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  135. return
  136. }
  137. addons = append(addons, addon)
  138. }
  139. if request.Base64PorterYAML != "" {
  140. decoded, err := base64.StdEncoding.DecodeString(request.Base64PorterYAML)
  141. if err != nil {
  142. err := telemetry.Error(ctx, span, err, "error decoding base yaml")
  143. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  144. return
  145. }
  146. appFromYaml, err := porter_app.ParseYAML(ctx, decoded, request.Name)
  147. if err != nil {
  148. err := telemetry.Error(ctx, span, err, "error parsing yaml")
  149. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  150. return
  151. }
  152. appProto = appFromYaml.AppProto
  153. // only public variables can be defined in porter.yaml
  154. envVariables = mergeEnvVariables(request.Variables, appFromYaml.EnvVariables)
  155. if appFromYaml.PreviewApp != nil {
  156. overrides = appFromYaml.PreviewApp.AppProto
  157. addonOverrides = appFromYaml.PreviewApp.Addons
  158. envVariables = mergeEnvVariables(envVariables, appFromYaml.PreviewApp.EnvVariables)
  159. }
  160. addons = appFromYaml.Addons
  161. }
  162. if appProto.Name == "" {
  163. if request.Name == "" {
  164. err := telemetry.Error(ctx, span, nil, "app name is empty")
  165. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  166. return
  167. }
  168. appProto.Name = request.Name
  169. }
  170. sourceType, image, err := sourceFromAppAndGitSource(ctx, appProto, request.GitSource)
  171. if err != nil {
  172. err := telemetry.Error(ctx, span, err, "error getting source from app and git source")
  173. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  174. return
  175. }
  176. // create porter app if it doesn't exist for the given name
  177. _, err = porter_app.CreateOrGetAppRecord(ctx, porter_app.CreateOrGetAppRecordInput{
  178. ClusterID: cluster.ID,
  179. ProjectID: project.ID,
  180. Name: appProto.Name,
  181. SourceType: sourceType,
  182. GitBranch: request.GitSource.GitBranch,
  183. GitRepoName: request.GitSource.GitRepoName,
  184. GitRepoID: request.GitSource.GitRepoID,
  185. PorterYamlPath: request.PorterYAMLPath,
  186. Image: image,
  187. PorterAppRepository: c.Repo().PorterApp(),
  188. })
  189. if err != nil {
  190. err := telemetry.Error(ctx, span, err, "error creating or getting porter app")
  191. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  192. return
  193. }
  194. var serviceDeletions map[string]*porterv1.ServiceDeletions
  195. if request.Deletions.ServiceDeletions != nil {
  196. serviceDeletions = make(map[string]*porterv1.ServiceDeletions)
  197. for k, v := range request.Deletions.ServiceDeletions {
  198. serviceDeletions[k] = &porterv1.ServiceDeletions{
  199. DomainNames: v.DomainNames,
  200. IngressAnnotations: v.IngressAnnotationKeys,
  201. }
  202. }
  203. }
  204. if request.ImageTagOverride != "" {
  205. if appProto.Image == nil {
  206. appProto.Image = &porterv1.AppImage{}
  207. }
  208. appProto.Image.Tag = request.ImageTagOverride
  209. }
  210. updateReq := connect.NewRequest(&porterv1.UpdateAppRequest{
  211. ProjectId: int64(project.ID),
  212. DeploymentTargetIdentifier: &porterv1.DeploymentTargetIdentifier{
  213. Id: deploymentTargetID,
  214. },
  215. App: appProto,
  216. AppRevisionId: request.AppRevisionID,
  217. AppEnv: &porterv1.EnvGroupVariables{
  218. Normal: envVariables,
  219. Secret: request.Secrets,
  220. },
  221. Deletions: &porterv1.Deletions{
  222. ServiceNames: request.Deletions.ServiceNames,
  223. PredeployNames: request.Deletions.Predeploy,
  224. EnvVariableNames: request.Deletions.EnvVariableNames,
  225. EnvGroupNames: request.Deletions.EnvGroupNames,
  226. ServiceDeletions: serviceDeletions,
  227. },
  228. AppOverrides: overrides,
  229. CommitSha: request.CommitSHA,
  230. IsEnvOverride: request.IsEnvOverride,
  231. Addons: addons,
  232. AddonOverrides: addonOverrides,
  233. })
  234. ccpResp, err := c.Config().ClusterControlPlaneClient.UpdateApp(ctx, updateReq)
  235. if err != nil {
  236. err := telemetry.Error(ctx, span, err, "error calling ccp update app")
  237. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  238. return
  239. }
  240. if ccpResp == nil {
  241. err := telemetry.Error(ctx, span, err, "ccp resp is nil")
  242. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  243. return
  244. }
  245. if ccpResp.Msg == nil {
  246. err := telemetry.Error(ctx, span, err, "ccp resp msg is nil")
  247. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  248. return
  249. }
  250. if ccpResp.Msg.AppRevisionId == "" {
  251. err := telemetry.Error(ctx, span, err, "ccp resp app revision id is empty")
  252. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  253. return
  254. }
  255. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "resp-app-revision-id", Value: ccpResp.Msg.AppRevisionId})
  256. response := &UpdateAppResponse{
  257. AppRevisionId: ccpResp.Msg.AppRevisionId,
  258. AppName: appProto.Name,
  259. }
  260. c.WriteResult(w, r, response)
  261. }
  262. func sourceFromAppAndGitSource(ctx context.Context, appProto *porterv1.PorterApp, gitSource GitSource) (porter_app.SourceType, *porter_app.Image, error) {
  263. ctx, span := telemetry.NewSpan(ctx, "source-from-app-and-git-source")
  264. defer span.End()
  265. var sourceType porter_app.SourceType
  266. var image *porter_app.Image
  267. if appProto == nil {
  268. return sourceType, image, telemetry.Error(ctx, span, nil, "app proto is nil")
  269. }
  270. telemetry.WithAttributes(span,
  271. telemetry.AttributeKV{Key: "app-name", Value: appProto.Name},
  272. telemetry.AttributeKV{Key: "git-repo-id", Value: gitSource.GitRepoID},
  273. telemetry.AttributeKV{Key: "has-build", Value: appProto.Build != nil},
  274. telemetry.AttributeKV{Key: "has-image", Value: appProto.Image != nil},
  275. )
  276. if appProto.Build != nil {
  277. if gitSource.GitRepoID == 0 {
  278. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "source-type", Value: porter_app.SourceType_Local})
  279. return porter_app.SourceType_Local, image, nil
  280. }
  281. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "source-type", Value: porter_app.SourceType_Github})
  282. return porter_app.SourceType_Github, image, nil
  283. }
  284. if appProto.Image != nil {
  285. sourceType = porter_app.SourceType_DockerRegistry
  286. image = &porter_app.Image{
  287. Repository: appProto.Image.Repository,
  288. Tag: appProto.Image.Tag,
  289. }
  290. }
  291. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "source-type", Value: sourceType})
  292. return sourceType, image, nil
  293. }
  294. func mergeEnvVariables(currentEnv, previousEnv map[string]string) map[string]string {
  295. env := make(map[string]string)
  296. for k, v := range previousEnv {
  297. env[k] = v
  298. }
  299. for k, v := range currentEnv {
  300. env[k] = v
  301. }
  302. return env
  303. }