update_app.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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, err = v2.PatchApp(ctx, appFromYaml.AppProto, request.PatchOperations)
  191. if err != nil {
  192. err := telemetry.Error(ctx, span, err, "error patching app proto")
  193. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  194. return
  195. }
  196. // only public variables can be defined in porter.yaml
  197. envVariables = mergeEnvVariables(request.Variables, appFromYaml.EnvVariables)
  198. if appFromYaml.PreviewApp != nil {
  199. overrides = appFromYaml.PreviewApp.AppProto
  200. addonOverrides = appFromYaml.PreviewApp.Addons
  201. previewEnvVariables = appFromYaml.PreviewApp.EnvVariables
  202. }
  203. addons = appFromYaml.Addons
  204. }
  205. if appProto.Name == "" {
  206. if request.Name == "" {
  207. err := telemetry.Error(ctx, span, nil, "app name is empty")
  208. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  209. return
  210. }
  211. appProto.Name = request.Name
  212. }
  213. sourceType, image, err := sourceFromAppAndGitSource(ctx, appProto, request.GitSource)
  214. if err != nil {
  215. err := telemetry.Error(ctx, span, err, "error getting source from app and git source")
  216. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  217. return
  218. }
  219. // create porter app if it doesn't exist for the given name
  220. _, err = porter_app.CreateOrGetAppRecord(ctx, porter_app.CreateOrGetAppRecordInput{
  221. ClusterID: cluster.ID,
  222. ProjectID: project.ID,
  223. Name: appProto.Name,
  224. SourceType: sourceType,
  225. GitBranch: request.GitSource.GitBranch,
  226. GitRepoName: request.GitSource.GitRepoName,
  227. GitRepoID: request.GitSource.GitRepoID,
  228. PorterYamlPath: request.PorterYAMLPath,
  229. Image: image,
  230. PorterAppRepository: c.Repo().PorterApp(),
  231. })
  232. if err != nil {
  233. err := telemetry.Error(ctx, span, err, "error creating or getting porter app")
  234. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  235. return
  236. }
  237. var serviceDeletions map[string]*porterv1.ServiceDeletions
  238. if request.Deletions.ServiceDeletions != nil {
  239. serviceDeletions = make(map[string]*porterv1.ServiceDeletions)
  240. for k, v := range request.Deletions.ServiceDeletions {
  241. serviceDeletions[k] = &porterv1.ServiceDeletions{
  242. DomainNames: v.DomainNames,
  243. IngressAnnotations: v.IngressAnnotationKeys,
  244. }
  245. }
  246. }
  247. if request.ImageTagOverride != "" {
  248. if appProto.Image == nil {
  249. appProto.Image = &porterv1.AppImage{}
  250. }
  251. appProto.Image.Tag = request.ImageTagOverride
  252. }
  253. updateReq := connect.NewRequest(&porterv1.UpdateAppRequest{
  254. ProjectId: int64(project.ID),
  255. ClusterId: int64(cluster.ID),
  256. DeploymentTargetIdentifier: deploymentTargetIdentifer,
  257. App: appProto,
  258. AppRevisionId: request.AppRevisionID,
  259. AppEnv: &porterv1.EnvGroupVariables{
  260. Normal: envVariables,
  261. Secret: request.Secrets,
  262. },
  263. AppEnvOverrides: &porterv1.EnvGroupVariables{
  264. Normal: previewEnvVariables,
  265. },
  266. Deletions: &porterv1.Deletions{
  267. ServiceNames: request.Deletions.ServiceNames,
  268. PredeployNames: request.Deletions.Predeploy,
  269. EnvGroupNames: request.Deletions.EnvGroupNames,
  270. ServiceDeletions: serviceDeletions,
  271. EnvVariableDeletions: &porterv1.EnvVariableDeletions{
  272. Variables: request.Deletions.EnvVariableDeletions.Variables,
  273. Secrets: request.Deletions.EnvVariableDeletions.Secrets,
  274. },
  275. },
  276. AppOverrides: overrides,
  277. CommitSha: request.CommitSHA,
  278. IsEnvOverride: request.IsEnvOverride,
  279. Addons: addons,
  280. AddonOverrides: addonOverrides,
  281. IsPredeployEligible: request.WithPredeploy,
  282. Exact: request.Exact,
  283. })
  284. ccpResp, err := c.Config().ClusterControlPlaneClient.UpdateApp(ctx, updateReq)
  285. if err != nil {
  286. err := telemetry.Error(ctx, span, err, "error calling ccp update app")
  287. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  288. return
  289. }
  290. if ccpResp == nil {
  291. err := telemetry.Error(ctx, span, err, "ccp resp is nil")
  292. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  293. return
  294. }
  295. if ccpResp.Msg == nil {
  296. err := telemetry.Error(ctx, span, err, "ccp resp msg is nil")
  297. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  298. return
  299. }
  300. if ccpResp.Msg.AppRevisionId == "" {
  301. err := telemetry.Error(ctx, span, err, "ccp resp app revision id is empty")
  302. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  303. return
  304. }
  305. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "resp-app-revision-id", Value: ccpResp.Msg.AppRevisionId})
  306. response := &UpdateAppResponse{
  307. AppRevisionId: ccpResp.Msg.AppRevisionId,
  308. AppName: appProto.Name,
  309. }
  310. c.WriteResult(w, r, response)
  311. }
  312. func sourceFromAppAndGitSource(ctx context.Context, appProto *porterv1.PorterApp, gitSource GitSource) (porter_app.SourceType, *porter_app.Image, error) {
  313. ctx, span := telemetry.NewSpan(ctx, "source-from-app-and-git-source")
  314. defer span.End()
  315. var sourceType porter_app.SourceType
  316. var image *porter_app.Image
  317. if appProto == nil {
  318. return sourceType, image, telemetry.Error(ctx, span, nil, "app proto is nil")
  319. }
  320. telemetry.WithAttributes(span,
  321. telemetry.AttributeKV{Key: "app-name", Value: appProto.Name},
  322. telemetry.AttributeKV{Key: "git-repo-id", Value: gitSource.GitRepoID},
  323. telemetry.AttributeKV{Key: "has-build", Value: appProto.Build != nil},
  324. telemetry.AttributeKV{Key: "has-image", Value: appProto.Image != nil},
  325. )
  326. if appProto.Build != nil {
  327. if gitSource.GitRepoID == 0 {
  328. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "source-type", Value: porter_app.SourceType_Local})
  329. return porter_app.SourceType_Local, image, nil
  330. }
  331. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "source-type", Value: porter_app.SourceType_Github})
  332. return porter_app.SourceType_Github, image, nil
  333. }
  334. if appProto.Image != nil {
  335. sourceType = porter_app.SourceType_DockerRegistry
  336. image = &porter_app.Image{
  337. Repository: appProto.Image.Repository,
  338. Tag: appProto.Image.Tag,
  339. }
  340. }
  341. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "source-type", Value: sourceType})
  342. return sourceType, image, nil
  343. }
  344. func mergeEnvVariables(currentEnv, previousEnv map[string]string) map[string]string {
  345. env := make(map[string]string)
  346. for k, v := range previousEnv {
  347. env[k] = v
  348. }
  349. for k, v := range currentEnv {
  350. env[k] = v
  351. }
  352. return env
  353. }