update_app.go 15 KB

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