update_app.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. v2 "github.com/porter-dev/porter/internal/porter_app/v2"
  18. "github.com/porter-dev/porter/internal/telemetry"
  19. )
  20. // UpdateAppHandler is the handler for the POST /apps/update endpoint
  21. type UpdateAppHandler struct {
  22. handlers.PorterHandlerReadWriter
  23. authz.KubernetesAgentGetter
  24. }
  25. // NewUpdateAppHandler handles POST requests to the endpoint POST /apps/update
  26. func NewUpdateAppHandler(
  27. config *config.Config,
  28. decoderValidator shared.RequestDecoderValidator,
  29. writer shared.ResultWriter,
  30. ) *UpdateAppHandler {
  31. return &UpdateAppHandler{
  32. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  33. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  34. }
  35. }
  36. // ServiceDeletions are deletions to apply to a specific service
  37. type ServiceDeletions struct {
  38. DomainNames []string `json:"domain_names"`
  39. IngressAnnotationKeys []string `json:"ingress_annotation_keys"`
  40. }
  41. // EnvVariableDeletions is the set of keys to delete from the environment group
  42. type EnvVariableDeletions struct {
  43. // Variables is a set of variable keys to delete from the environment group
  44. Variables []string `json:"variables"`
  45. // Secrets is a set of secret variable keys to delete from the environment group
  46. Secrets []string `json:"secrets"`
  47. }
  48. // Deletions are the names of services and env variables to delete
  49. type Deletions struct {
  50. ServiceNames []string `json:"service_names"`
  51. Predeploy []string `json:"predeploy"`
  52. EnvGroupNames []string `json:"env_group_names"`
  53. ServiceDeletions map[string]ServiceDeletions `json:"service_deletions"`
  54. EnvVariableDeletions EnvVariableDeletions `json:"env_variable_deletions"`
  55. }
  56. // UpdateAppRequest is the request object for the POST /apps/update endpoint
  57. type UpdateAppRequest struct {
  58. // Name is the name of the app to update. If not specified, the name will be inferred from the porter yaml
  59. Name string `json:"name"`
  60. // GitSource is the git source configuration for the app, if applicable
  61. GitSource GitSource `json:"git_source,omitempty"`
  62. // DeploymentTargetId is the ID of the deployment target to apply the update to
  63. DeploymentTargetId string `json:"deployment_target_id"`
  64. // DeploymentTargetName is the name of the deployment target to apply the update to
  65. DeploymentTargetName string `json:"deployment_target_name"`
  66. // Variables is a map of environment variable names to values
  67. Variables map[string]string `json:"variables"`
  68. // Secrets is a map of secret names to values
  69. Secrets map[string]string `json:"secrets"`
  70. // Deletions is the set of fields to delete before applying the update
  71. Deletions Deletions `json:"deletions"`
  72. // CommitSHA is the commit sha of the git commit that triggered this update, indicating a source change and triggering a build
  73. CommitSHA string `json:"commit_sha"`
  74. // 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)
  75. ImageTagOverride string `json:"image_tag_override"`
  76. // PorterYAMLPath is the path to the porter yaml file in the git repo
  77. PorterYAMLPath string `json:"porter_yaml_path"`
  78. // AppRevisionID is the ID of the revision to perform follow up actions on after the initial apply
  79. AppRevisionID string `json:"app_revision_id"`
  80. // Only one of Base64AppProto or Base64PorterYAML should be specified
  81. // Base64AppProto is a ful base64 encoded porter app contract to apply
  82. Base64AppProto string `json:"b64_app_proto"`
  83. // Base64AddonProtos is a list of base64 encoded addon contracts to apply along with the app
  84. Base64AddonProtos []string `json:"b64_addon_protos"`
  85. // Base64PorterYAML is a base64 encoded porter yaml to apply representing a potentially partial porter app contract
  86. Base64PorterYAML string `json:"b64_porter_yaml"`
  87. // PatchOperations is a set of patch operations to apply to the porter.yaml if specified
  88. PatchOperations []v2.PatchOperation `json:"patch_operations"`
  89. // 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,
  90. // and leave all other variables untouched.
  91. IsEnvOverride bool `json:"is_env_override"`
  92. // WithPredeploy is a flag to indicate whether to run the predeploy job
  93. WithPredeploy bool `json:"with_predeploy"`
  94. // Exact is a flag to indicate whether to apply the update exactly as specified in the request (default is to merge with existing app)
  95. Exact bool `json:"exact"`
  96. }
  97. // UpdateAppResponse is the response object for the POST /apps/update endpoint
  98. type UpdateAppResponse struct {
  99. AppName string `json:"app_name"`
  100. AppRevisionId string `json:"app_revision_id"`
  101. }
  102. // ServeHTTP translates the request into an UpdateApp request, forwards to the cluster control plane, and returns the response
  103. func (c *UpdateAppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  104. ctx, span := telemetry.NewSpan(r.Context(), "serve-update-app")
  105. defer span.End()
  106. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  107. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  108. request := &UpdateAppRequest{}
  109. if ok := c.DecodeAndValidate(w, r, request); !ok {
  110. err := telemetry.Error(ctx, span, nil, "error decoding request")
  111. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  112. return
  113. }
  114. if request.Base64AppProto != "" && request.Base64PorterYAML != "" {
  115. err := telemetry.Error(ctx, span, nil, "both b64 yaml and b64 porter yaml are specified")
  116. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  117. return
  118. }
  119. deploymentTargetID := request.DeploymentTargetId
  120. deploymentTargetName := request.DeploymentTargetName
  121. telemetry.WithAttributes(span,
  122. telemetry.AttributeKV{Key: "deployment-target-id", Value: deploymentTargetID},
  123. telemetry.AttributeKV{Key: "deployment-target-name", Value: deploymentTargetName},
  124. )
  125. var deploymentTargetIdentifer *porterv1.DeploymentTargetIdentifier
  126. if deploymentTargetID != "" || deploymentTargetName != "" {
  127. deploymentTargetIdentifer = &porterv1.DeploymentTargetIdentifier{
  128. Id: deploymentTargetID,
  129. Name: deploymentTargetName,
  130. }
  131. }
  132. telemetry.WithAttributes(span,
  133. telemetry.AttributeKV{Key: "name", Value: request.Name},
  134. telemetry.AttributeKV{Key: "deployment-target-id", Value: deploymentTargetID},
  135. telemetry.AttributeKV{Key: "app-revision-id", Value: request.AppRevisionID},
  136. telemetry.AttributeKV{Key: "commit-sha", Value: request.CommitSHA},
  137. telemetry.AttributeKV{Key: "porter-yaml-path", Value: request.PorterYAMLPath},
  138. telemetry.AttributeKV{Key: "is-env-override", Value: request.IsEnvOverride},
  139. telemetry.AttributeKV{Key: "with-predeploy", Value: request.WithPredeploy},
  140. )
  141. var addons, addonOverrides []*porterv1.Addon
  142. var overrides *porterv1.PorterApp
  143. appProto := &porterv1.PorterApp{}
  144. var previewEnvVariables map[string]string
  145. envVariables := request.Variables
  146. // get app definition from either base64 yaml or base64 porter app proto
  147. if request.Base64AppProto != "" {
  148. decoded, err := base64.StdEncoding.DecodeString(request.Base64AppProto)
  149. if err != nil {
  150. err := telemetry.Error(ctx, span, err, "error decoding base yaml")
  151. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  152. return
  153. }
  154. err = helpers.UnmarshalContractObject(decoded, appProto)
  155. if err != nil {
  156. err := telemetry.Error(ctx, span, err, "error unmarshalling app proto")
  157. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  158. return
  159. }
  160. }
  161. for _, b64AddonProto := range request.Base64AddonProtos {
  162. decoded, err := base64.StdEncoding.DecodeString(b64AddonProto)
  163. if err != nil {
  164. err := telemetry.Error(ctx, span, err, "error decoding base yaml")
  165. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  166. return
  167. }
  168. addon := &porterv1.Addon{}
  169. err = helpers.UnmarshalContractObject(decoded, addon)
  170. if err != nil {
  171. err := telemetry.Error(ctx, span, err, "error unmarshalling addon proto")
  172. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  173. return
  174. }
  175. addons = append(addons, addon)
  176. }
  177. if request.Base64PorterYAML != "" {
  178. decoded, err := base64.StdEncoding.DecodeString(request.Base64PorterYAML)
  179. if err != nil {
  180. err := telemetry.Error(ctx, span, err, "error decoding base yaml")
  181. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  182. return
  183. }
  184. appFromYaml, err := porter_app.ParseYAML(ctx, decoded, request.Name)
  185. if err != nil {
  186. err := telemetry.Error(ctx, span, err, "error parsing yaml")
  187. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  188. return
  189. }
  190. appProto = appFromYaml.AppProto
  191. // only public variables can be defined in porter.yaml
  192. envVariables = mergeEnvVariables(request.Variables, appFromYaml.EnvVariables)
  193. if appFromYaml.PreviewApp != nil {
  194. overrides = appFromYaml.PreviewApp.AppProto
  195. addonOverrides = appFromYaml.PreviewApp.Addons
  196. previewEnvVariables = appFromYaml.PreviewApp.EnvVariables
  197. }
  198. addons = appFromYaml.Addons
  199. }
  200. if appProto != nil {
  201. patchedProto, err := v2.PatchApp(ctx, appProto, request.PatchOperations)
  202. if err != nil {
  203. err := telemetry.Error(ctx, span, err, "error patching app proto")
  204. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  205. return
  206. }
  207. appProto = patchedProto
  208. }
  209. if appProto.Name == "" {
  210. if request.Name == "" {
  211. err := telemetry.Error(ctx, span, nil, "app name is empty")
  212. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  213. return
  214. }
  215. appProto.Name = request.Name
  216. }
  217. sourceType, image, err := sourceFromAppAndGitSource(ctx, appProto, request.GitSource)
  218. if err != nil {
  219. err := telemetry.Error(ctx, span, err, "error getting source from app and git source")
  220. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  221. return
  222. }
  223. // create porter app if it doesn't exist for the given name
  224. _, err = porter_app.CreateOrGetAppRecord(ctx, porter_app.CreateOrGetAppRecordInput{
  225. ClusterID: cluster.ID,
  226. ProjectID: project.ID,
  227. Name: appProto.Name,
  228. SourceType: sourceType,
  229. GitBranch: request.GitSource.GitBranch,
  230. GitRepoName: request.GitSource.GitRepoName,
  231. GitRepoID: request.GitSource.GitRepoID,
  232. PorterYamlPath: request.PorterYAMLPath,
  233. Image: image,
  234. PorterAppRepository: c.Repo().PorterApp(),
  235. })
  236. if err != nil {
  237. err := telemetry.Error(ctx, span, err, "error creating or getting porter app")
  238. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  239. return
  240. }
  241. var serviceDeletions map[string]*porterv1.ServiceDeletions
  242. if request.Deletions.ServiceDeletions != nil {
  243. serviceDeletions = make(map[string]*porterv1.ServiceDeletions)
  244. for k, v := range request.Deletions.ServiceDeletions {
  245. serviceDeletions[k] = &porterv1.ServiceDeletions{
  246. DomainNames: v.DomainNames,
  247. IngressAnnotations: v.IngressAnnotationKeys,
  248. }
  249. }
  250. }
  251. if request.ImageTagOverride != "" {
  252. if appProto.Image == nil {
  253. appProto.Image = &porterv1.AppImage{}
  254. }
  255. appProto.Image.Tag = request.ImageTagOverride
  256. }
  257. updateReq := connect.NewRequest(&porterv1.UpdateAppRequest{
  258. ProjectId: int64(project.ID),
  259. ClusterId: int64(cluster.ID),
  260. DeploymentTargetIdentifier: deploymentTargetIdentifer,
  261. App: appProto,
  262. AppRevisionId: request.AppRevisionID,
  263. AppEnv: &porterv1.EnvGroupVariables{
  264. Normal: envVariables,
  265. Secret: request.Secrets,
  266. },
  267. AppEnvOverrides: &porterv1.EnvGroupVariables{
  268. Normal: previewEnvVariables,
  269. },
  270. Deletions: &porterv1.Deletions{
  271. ServiceNames: request.Deletions.ServiceNames,
  272. PredeployNames: request.Deletions.Predeploy,
  273. EnvGroupNames: request.Deletions.EnvGroupNames,
  274. ServiceDeletions: serviceDeletions,
  275. EnvVariableDeletions: &porterv1.EnvVariableDeletions{
  276. Variables: request.Deletions.EnvVariableDeletions.Variables,
  277. Secrets: request.Deletions.EnvVariableDeletions.Secrets,
  278. },
  279. },
  280. AppOverrides: overrides,
  281. CommitSha: request.CommitSHA,
  282. IsEnvOverride: request.IsEnvOverride,
  283. Addons: addons,
  284. AddonOverrides: addonOverrides,
  285. IsPredeployEligible: request.WithPredeploy,
  286. Exact: request.Exact,
  287. })
  288. ccpResp, err := c.Config().ClusterControlPlaneClient.UpdateApp(ctx, updateReq)
  289. if err != nil {
  290. err := telemetry.Error(ctx, span, err, "error calling ccp update app")
  291. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  292. return
  293. }
  294. if ccpResp == nil {
  295. err := telemetry.Error(ctx, span, err, "ccp resp is nil")
  296. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  297. return
  298. }
  299. if ccpResp.Msg == nil {
  300. err := telemetry.Error(ctx, span, err, "ccp resp msg is nil")
  301. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  302. return
  303. }
  304. if ccpResp.Msg.AppRevisionId == "" {
  305. err := telemetry.Error(ctx, span, err, "ccp resp app revision id is empty")
  306. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  307. return
  308. }
  309. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "resp-app-revision-id", Value: ccpResp.Msg.AppRevisionId})
  310. response := &UpdateAppResponse{
  311. AppRevisionId: ccpResp.Msg.AppRevisionId,
  312. AppName: appProto.Name,
  313. }
  314. c.WriteResult(w, r, response)
  315. }
  316. func sourceFromAppAndGitSource(ctx context.Context, appProto *porterv1.PorterApp, gitSource GitSource) (porter_app.SourceType, *porter_app.Image, error) {
  317. ctx, span := telemetry.NewSpan(ctx, "source-from-app-and-git-source")
  318. defer span.End()
  319. var sourceType porter_app.SourceType
  320. var image *porter_app.Image
  321. if appProto == nil {
  322. return sourceType, image, telemetry.Error(ctx, span, nil, "app proto is nil")
  323. }
  324. telemetry.WithAttributes(span,
  325. telemetry.AttributeKV{Key: "app-name", Value: appProto.Name},
  326. telemetry.AttributeKV{Key: "git-repo-id", Value: gitSource.GitRepoID},
  327. telemetry.AttributeKV{Key: "has-build", Value: appProto.Build != nil},
  328. telemetry.AttributeKV{Key: "has-image", Value: appProto.Image != nil},
  329. )
  330. if appProto.Build != nil {
  331. if gitSource.GitRepoID == 0 {
  332. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "source-type", Value: porter_app.SourceType_Local})
  333. return porter_app.SourceType_Local, image, nil
  334. }
  335. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "source-type", Value: porter_app.SourceType_Github})
  336. return porter_app.SourceType_Github, image, nil
  337. }
  338. if appProto.Image != nil {
  339. sourceType = porter_app.SourceType_DockerRegistry
  340. image = &porter_app.Image{
  341. Repository: appProto.Image.Repository,
  342. Tag: appProto.Image.Tag,
  343. }
  344. }
  345. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "source-type", Value: sourceType})
  346. return sourceType, image, nil
  347. }
  348. func mergeEnvVariables(currentEnv, previousEnv map[string]string) map[string]string {
  349. env := make(map[string]string)
  350. for k, v := range previousEnv {
  351. env[k] = v
  352. }
  353. for k, v := range currentEnv {
  354. env[k] = v
  355. }
  356. return env
  357. }