GitOps for k8s
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sync_cmd.go 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "github.com/spf13/cobra"
  7. "github.com/fluxcd/flux/git"
  8. "github.com/fluxcd/flux/update"
  9. )
  10. type syncOpts struct {
  11. *rootOpts
  12. }
  13. func newSync(parent *rootOpts) *syncOpts {
  14. return &syncOpts{rootOpts: parent}
  15. }
  16. func (opts *syncOpts) Command() *cobra.Command {
  17. cmd := &cobra.Command{
  18. Use: "sync",
  19. Short: "synchronize the cluster with the git repository, now",
  20. RunE: opts.RunE,
  21. }
  22. return cmd
  23. }
  24. func (opts *syncOpts) RunE(cmd *cobra.Command, args []string) error {
  25. if len(args) > 0 {
  26. return errorWantedNoArgs
  27. }
  28. ctx := context.Background()
  29. gitConfig, err := opts.API.GitRepoConfig(ctx, false)
  30. if err != nil {
  31. return err
  32. }
  33. switch gitConfig.Status {
  34. case git.RepoNoConfig:
  35. return fmt.Errorf("no git repository is configured")
  36. case git.RepoReady:
  37. break
  38. default:
  39. return fmt.Errorf("git repository %s is not ready to sync (status: %s)", gitConfig.Remote.URL, string(gitConfig.Status))
  40. }
  41. fmt.Fprintf(cmd.OutOrStderr(), "Synchronizing with %s\n", gitConfig.Remote.URL)
  42. updateSpec := update.Spec{
  43. Type: update.Sync,
  44. Spec: update.ManualSync{},
  45. }
  46. jobID, err := opts.API.UpdateManifests(ctx, updateSpec)
  47. if err != nil {
  48. return err
  49. }
  50. result, err := awaitJob(ctx, opts.API, jobID, opts.Timeout)
  51. if isUnverifiedHead(err) {
  52. fmt.Fprintf(cmd.OutOrStderr(), "Warning: %s\n", err)
  53. } else if err != nil {
  54. fmt.Fprintf(cmd.OutOrStderr(), "Failed to complete sync job (ID %q)\n", jobID)
  55. return err
  56. }
  57. rev := result.Revision[:7]
  58. fmt.Fprintf(cmd.OutOrStderr(), "Revision of %s to apply is %s\n", gitConfig.Remote.Branch, rev)
  59. fmt.Fprintf(cmd.OutOrStderr(), "Waiting for %s to be applied ...\n", rev)
  60. err = awaitSync(ctx, opts.API, rev, opts.Timeout)
  61. if err != nil {
  62. return err
  63. }
  64. fmt.Fprintln(cmd.OutOrStderr(), "Done.")
  65. return nil
  66. }
  67. func isUnverifiedHead(err error) bool {
  68. return err != nil &&
  69. (strings.Contains(err.Error(), "branch HEAD in the git repo is not verified") &&
  70. strings.Contains(err.Error(), "last verified commit was"))
  71. }