bluegreen.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "time"
  7. "github.com/fatih/color"
  8. api "github.com/porter-dev/porter/api/client"
  9. "github.com/porter-dev/porter/api/types"
  10. "github.com/porter-dev/porter/cli/cmd/deploy"
  11. "github.com/spf13/cobra"
  12. appsv1 "k8s.io/api/apps/v1"
  13. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  14. intstrutil "k8s.io/apimachinery/pkg/util/intstr"
  15. )
  16. var deployCmd = &cobra.Command{
  17. Use: "deploy",
  18. }
  19. var bluegreenCmd = &cobra.Command{
  20. Use: "blue-green-switch",
  21. Short: "Automatically switches the traffic of a blue-green deployment once the new application is ready.",
  22. Run: func(cmd *cobra.Command, args []string) {
  23. err := checkLoginAndRun(args, bluegreenSwitch)
  24. if err != nil {
  25. os.Exit(1)
  26. }
  27. },
  28. }
  29. func init() {
  30. rootCmd.AddCommand(deployCmd)
  31. deployCmd.AddCommand(bluegreenCmd)
  32. bluegreenCmd.PersistentFlags().StringVar(
  33. &app,
  34. "app",
  35. "",
  36. "Application in the Porter dashboard",
  37. )
  38. bluegreenCmd.MarkPersistentFlagRequired("app")
  39. bluegreenCmd.PersistentFlags().StringVar(
  40. &tag,
  41. "tag",
  42. "",
  43. "The image tag to switch traffic to.",
  44. )
  45. bluegreenCmd.PersistentFlags().StringVar(
  46. &namespace,
  47. "namespace",
  48. "",
  49. "The namespace of the jobs.",
  50. )
  51. }
  52. func bluegreenSwitch(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  53. // get the web release
  54. webRelease, err := client.GetRelease(context.Background(), cliConf.Project, cliConf.Cluster, namespace, app)
  55. if err != nil {
  56. return err
  57. }
  58. // if this application is not a web chart, throw an error
  59. if webRelease.Chart.Name() != "web" {
  60. return fmt.Errorf("target application is not a web chart")
  61. }
  62. currActiveImage := deploy.GetCurrActiveBlueGreenImage(webRelease.Config)
  63. sharedConf := &PorterRunSharedConfig{
  64. Client: client,
  65. }
  66. err = sharedConf.setSharedConfig()
  67. if err != nil {
  68. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  69. }
  70. // if no job exists with the given revision, wait up to 30 minutes
  71. timeWait := time.Now().Add(30 * time.Minute)
  72. prevRefresh := time.Now()
  73. success := false
  74. color.New(color.FgGreen).Printf("Waiting for the new version of the application %s to be ready\n", app)
  75. for time.Now().Before(timeWait) {
  76. // refresh the client every 10 minutes
  77. if time.Now().After(prevRefresh.Add(10 * time.Minute)) {
  78. err = sharedConf.setSharedConfig()
  79. if err != nil {
  80. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  81. }
  82. prevRefresh = time.Now()
  83. }
  84. depls, err := sharedConf.Clientset.AppsV1().Deployments(namespace).List(
  85. context.Background(),
  86. metav1.ListOptions{
  87. LabelSelector: fmt.Sprintf("app.kubernetes.io/instance=%s", app),
  88. },
  89. )
  90. if err != nil {
  91. return fmt.Errorf("could not get deployments: %s", err.Error())
  92. }
  93. foundDeployment := false
  94. // get the deployment which matches the new image tag
  95. for _, depl := range depls.Items {
  96. if depl.ObjectMeta.Name == fmt.Sprintf("%s-web-%s", app, tag) || depl.ObjectMeta.Name == fmt.Sprintf("%s-%s", app, tag) {
  97. foundDeployment = true
  98. // determine if the deployment has an appropriate number of ready replicas
  99. minUnavailable := *(depl.Spec.Replicas) - getMaxUnavailable(depl)
  100. // if the number of ready replicas is greater than the number of min unavailable,
  101. // the controller is ready for a traffic switch
  102. if minUnavailable <= depl.Status.ReadyReplicas {
  103. // push the deployment
  104. color.New(color.FgGreen).Printf("Switching traffic for app %s\n", app)
  105. deployAgent, err := updateGetAgent(client)
  106. if err != nil {
  107. return err
  108. }
  109. if currActiveImage == "" {
  110. err = deployAgent.UpdateImageAndValues(map[string]interface{}{
  111. "bluegreen": map[string]interface{}{
  112. "enabled": true,
  113. "disablePrimaryDeployment": true,
  114. "activeImageTag": tag,
  115. "imageTags": []string{tag},
  116. },
  117. })
  118. } else {
  119. err = deployAgent.UpdateImageAndValues(map[string]interface{}{
  120. "bluegreen": map[string]interface{}{
  121. "enabled": true,
  122. "disablePrimaryDeployment": true,
  123. "activeImageTag": tag,
  124. "imageTags": []string{currActiveImage, tag},
  125. },
  126. })
  127. }
  128. if err != nil {
  129. return err
  130. } else {
  131. success = true
  132. }
  133. }
  134. }
  135. }
  136. if !foundDeployment {
  137. return fmt.Errorf("target deployment not found. Did you specify the correct tag?")
  138. }
  139. if success {
  140. break
  141. }
  142. // otherwise, return no error
  143. time.Sleep(2 * time.Second)
  144. }
  145. if !success {
  146. return fmt.Errorf("new application was not ready within 30 minutes")
  147. }
  148. // wait 30 seconds before removing old deployment
  149. time.Sleep(30 * time.Second)
  150. deployAgent, err := updateGetAgent(client)
  151. if err != nil {
  152. return err
  153. }
  154. err = deployAgent.UpdateImageAndValues(map[string]interface{}{
  155. "bluegreen": map[string]interface{}{
  156. "enabled": true,
  157. "disablePrimaryDeployment": true,
  158. "activeImageTag": tag,
  159. "imageTags": []string{tag},
  160. },
  161. })
  162. return nil
  163. }
  164. func getMaxUnavailable(deployment appsv1.Deployment) int32 {
  165. if deployment.Spec.Strategy.Type != appsv1.RollingUpdateDeploymentStrategyType || *(deployment.Spec.Replicas) == 0 {
  166. return int32(0)
  167. }
  168. desired := *(deployment.Spec.Replicas)
  169. maxUnavailable := deployment.Spec.Strategy.RollingUpdate.MaxUnavailable
  170. unavailable, err := intstrutil.GetScaledValueFromIntOrPercent(intstrutil.ValueOrDefault(maxUnavailable, intstrutil.FromInt(0)), int(desired), false)
  171. if err != nil {
  172. return 0
  173. }
  174. return int32(unavailable)
  175. }