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.

release_image.go 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package update
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/pkg/errors"
  6. "github.com/go-kit/kit/log"
  7. "github.com/weaveworks/flux"
  8. "github.com/weaveworks/flux/image"
  9. "github.com/weaveworks/flux/policy"
  10. "github.com/weaveworks/flux/registry"
  11. )
  12. const (
  13. ResourceSpecAll = ResourceSpec("<all>")
  14. ImageSpecLatest = ImageSpec("<all latest>")
  15. )
  16. var (
  17. ErrInvalidReleaseKind = errors.New("invalid release kind")
  18. )
  19. // ReleaseKind says whether a release is to be planned only, or planned then executed
  20. type ReleaseKind string
  21. type ReleaseType string
  22. const (
  23. ReleaseKindPlan ReleaseKind = "plan"
  24. ReleaseKindExecute ReleaseKind = "execute"
  25. )
  26. func ParseReleaseKind(s string) (ReleaseKind, error) {
  27. switch s {
  28. case string(ReleaseKindPlan):
  29. return ReleaseKindPlan, nil
  30. case string(ReleaseKindExecute):
  31. return ReleaseKindExecute, nil
  32. default:
  33. return "", ErrInvalidReleaseKind
  34. }
  35. }
  36. const UserAutomated = "<automated>"
  37. type ReleaseContext interface {
  38. SelectWorkloads(Result, []WorkloadFilter, []WorkloadFilter) ([]*WorkloadUpdate, error)
  39. Registry() registry.Registry
  40. }
  41. // NB: these get sent from fluxctl, so we have to maintain the json format of
  42. // this. Eugh.
  43. type ReleaseImageSpec struct {
  44. ServiceSpecs []ResourceSpec // TODO: rename to WorkloadSpecs after adding versioning
  45. ImageSpec ImageSpec
  46. Kind ReleaseKind
  47. Excludes []flux.ResourceID
  48. Force bool
  49. }
  50. // ReleaseType gives a one-word description of the release, mainly
  51. // useful for labelling metrics or log messages.
  52. func (s ReleaseImageSpec) ReleaseType() ReleaseType {
  53. switch {
  54. case s.ImageSpec == ImageSpecLatest:
  55. return "latest_images"
  56. default:
  57. return "specific_image"
  58. }
  59. }
  60. func (s ReleaseImageSpec) CalculateRelease(rc ReleaseContext, logger log.Logger) ([]*WorkloadUpdate, Result, error) {
  61. results := Result{}
  62. timer := NewStageTimer("select_workloads")
  63. updates, err := s.selectWorkloads(rc, results)
  64. timer.ObserveDuration()
  65. if err != nil {
  66. return nil, nil, err
  67. }
  68. s.markSkipped(results)
  69. timer = NewStageTimer("lookup_images")
  70. updates, err = s.calculateImageUpdates(rc, updates, results, logger)
  71. timer.ObserveDuration()
  72. if err != nil {
  73. return nil, nil, err
  74. }
  75. return updates, results, nil
  76. }
  77. func (s ReleaseImageSpec) ReleaseKind() ReleaseKind {
  78. return s.Kind
  79. }
  80. func (s ReleaseImageSpec) CommitMessage(result Result) string {
  81. image := strings.Trim(s.ImageSpec.String(), "<>")
  82. var workloads []string
  83. for _, spec := range s.ServiceSpecs {
  84. workloads = append(workloads, strings.Trim(spec.String(), "<>"))
  85. }
  86. return fmt.Sprintf("Release %s to %s", image, strings.Join(workloads, ", "))
  87. }
  88. // Take the spec given in the job, and figure out which workloads are
  89. // in question based on the running workloads and those defined in the
  90. // repo. Fill in the release results along the way.
  91. func (s ReleaseImageSpec) selectWorkloads(rc ReleaseContext, results Result) ([]*WorkloadUpdate, error) {
  92. // Build list of filters
  93. prefilters, postfilters, err := s.filters(rc)
  94. if err != nil {
  95. return nil, err
  96. }
  97. // Find and filter workloads
  98. return rc.SelectWorkloads(results, prefilters, postfilters)
  99. }
  100. func (s ReleaseImageSpec) filters(rc ReleaseContext) ([]WorkloadFilter, []WorkloadFilter, error) {
  101. var prefilters, postfilters []WorkloadFilter
  102. ids := []flux.ResourceID{}
  103. for _, ss := range s.ServiceSpecs {
  104. if ss == ResourceSpecAll {
  105. // "<all>" Overrides any other filters
  106. ids = []flux.ResourceID{}
  107. break
  108. }
  109. id, err := flux.ParseResourceID(string(ss))
  110. if err != nil {
  111. return nil, nil, err
  112. }
  113. ids = append(ids, id)
  114. }
  115. if len(ids) > 0 {
  116. prefilters = append(prefilters, &IncludeFilter{ids})
  117. }
  118. // Exclude filter
  119. if len(s.Excludes) > 0 {
  120. prefilters = append(prefilters, &ExcludeFilter{s.Excludes})
  121. }
  122. // Image filter
  123. if s.ImageSpec != ImageSpecLatest {
  124. id, err := image.ParseRef(s.ImageSpec.String())
  125. if err != nil {
  126. return nil, nil, err
  127. }
  128. postfilters = append(postfilters, &SpecificImageFilter{id})
  129. }
  130. // Filter out locked controllers unless given a specific controller(s) and forced
  131. if !(len(ids) > 0 && s.Force) {
  132. postfilters = append(postfilters, &LockedFilter{}, &IgnoreFilter{})
  133. }
  134. return prefilters, postfilters, nil
  135. }
  136. func (s ReleaseImageSpec) markSkipped(results Result) {
  137. for _, v := range s.ServiceSpecs {
  138. if v == ResourceSpecAll {
  139. continue
  140. }
  141. id, err := v.AsID()
  142. if err != nil {
  143. continue
  144. }
  145. if _, ok := results[id]; !ok {
  146. results[id] = WorkloadResult{
  147. Status: ReleaseStatusSkipped,
  148. Error: NotInRepo,
  149. }
  150. }
  151. }
  152. }
  153. // Find all the image updates that should be performed, and do
  154. // replacements. (For a dry-run, we don't strictly need to do the
  155. // replacements, since we won't be committing any changes back;
  156. // however we do want to see if we *can* do the replacements, because
  157. // if not, it indicates there's likely some problem with the running
  158. // system vs the definitions given in the repo.)
  159. func (s ReleaseImageSpec) calculateImageUpdates(rc ReleaseContext, candidates []*WorkloadUpdate, results Result, logger log.Logger) ([]*WorkloadUpdate, error) {
  160. // Compile an `ImageRepos` of all relevant images
  161. var imageRepos ImageRepos
  162. var singleRepo image.CanonicalName
  163. var err error
  164. switch s.ImageSpec {
  165. case ImageSpecLatest:
  166. imageRepos, err = fetchUpdatableImageRepos(rc.Registry(), candidates, logger)
  167. default:
  168. var ref image.Ref
  169. ref, err = s.ImageSpec.AsRef()
  170. if err == nil {
  171. singleRepo = ref.CanonicalName()
  172. imageRepos, err = exactImageRepos(rc.Registry(), []image.Ref{ref})
  173. }
  174. }
  175. if err != nil {
  176. return nil, err
  177. }
  178. // Look through all the workloads' containers to see which have an
  179. // image that could be updated.
  180. var updates []*WorkloadUpdate
  181. for _, u := range candidates {
  182. containers, err := u.Workload.ContainersOrError()
  183. if err != nil {
  184. results[u.ResourceID] = WorkloadResult{
  185. Status: ReleaseStatusFailed,
  186. Error: err.Error(),
  187. }
  188. continue
  189. }
  190. // If at least one container used an image in question, we say
  191. // we're skipping it rather than ignoring it. This is mainly
  192. // for the purpose of filtering the output.
  193. ignoredOrSkipped := ReleaseStatusIgnored
  194. var containerUpdates []ContainerUpdate
  195. for _, container := range containers {
  196. currentImageID := container.Image
  197. tagPattern := policy.PatternAll
  198. // Use the container's filter if the spec does not want to force release, or
  199. // all images requested
  200. if !s.Force || s.ImageSpec == ImageSpecLatest {
  201. if pattern, ok := u.Resource.Policies().Get(policy.TagPrefix(container.Name)); ok {
  202. tagPattern = policy.NewPattern(pattern)
  203. }
  204. }
  205. filteredImages := imageRepos.GetRepoImages(currentImageID.Name).FilterAndSort(tagPattern)
  206. latestImage, ok := filteredImages.Latest()
  207. if !ok {
  208. if currentImageID.CanonicalName() != singleRepo {
  209. ignoredOrSkipped = ReleaseStatusIgnored
  210. } else {
  211. ignoredOrSkipped = ReleaseStatusUnknown
  212. }
  213. continue
  214. }
  215. if currentImageID == latestImage.ID {
  216. ignoredOrSkipped = ReleaseStatusSkipped
  217. continue
  218. }
  219. // We want to update the image with respect to the form it
  220. // appears in the manifest, whereas what we have is the
  221. // canonical form.
  222. newImageID := currentImageID.WithNewTag(latestImage.ID.Tag)
  223. containerUpdates = append(containerUpdates, ContainerUpdate{
  224. Container: container.Name,
  225. Current: currentImageID,
  226. Target: newImageID,
  227. })
  228. }
  229. switch {
  230. case len(containerUpdates) > 0:
  231. u.Updates = containerUpdates
  232. updates = append(updates, u)
  233. results[u.ResourceID] = WorkloadResult{
  234. Status: ReleaseStatusSuccess,
  235. PerContainer: containerUpdates,
  236. }
  237. case ignoredOrSkipped == ReleaseStatusSkipped:
  238. results[u.ResourceID] = WorkloadResult{
  239. Status: ReleaseStatusSkipped,
  240. Error: ImageUpToDate,
  241. }
  242. case ignoredOrSkipped == ReleaseStatusIgnored:
  243. results[u.ResourceID] = WorkloadResult{
  244. Status: ReleaseStatusIgnored,
  245. Error: DoesNotUseImage,
  246. }
  247. case ignoredOrSkipped == ReleaseStatusUnknown:
  248. results[u.ResourceID] = WorkloadResult{
  249. Status: ReleaseStatusSkipped,
  250. Error: ImageNotFound,
  251. }
  252. }
  253. }
  254. return updates, nil
  255. }
  256. type ResourceSpec string // ResourceID or "<all>"
  257. func ParseResourceSpec(s string) (ResourceSpec, error) {
  258. if s == string(ResourceSpecAll) {
  259. return ResourceSpecAll, nil
  260. }
  261. id, err := flux.ParseResourceID(s)
  262. if err != nil {
  263. return "", errors.Wrap(err, "invalid workload spec")
  264. }
  265. return ResourceSpec(id.String()), nil
  266. }
  267. func MakeResourceSpec(id flux.ResourceID) ResourceSpec {
  268. return ResourceSpec(id.String())
  269. }
  270. func (s ResourceSpec) AsID() (flux.ResourceID, error) {
  271. return flux.ParseResourceID(string(s))
  272. }
  273. func (s ResourceSpec) String() string {
  274. return string(s)
  275. }
  276. // ImageSpec is an ImageID, or "<all latest>" (update all containers
  277. // to the latest available).
  278. type ImageSpec string
  279. func ParseImageSpec(s string) (ImageSpec, error) {
  280. if s == string(ImageSpecLatest) {
  281. return ImageSpecLatest, nil
  282. }
  283. id, err := image.ParseRef(s)
  284. if err != nil {
  285. return "", err
  286. }
  287. if id.Tag == "" {
  288. return "", errors.Wrap(image.ErrInvalidImageID, "blank tag (if you want latest, explicitly state the tag :latest)")
  289. }
  290. return ImageSpec(id.String()), err
  291. }
  292. func (s ImageSpec) String() string {
  293. return string(s)
  294. }
  295. func (s ImageSpec) AsRef() (image.Ref, error) {
  296. return image.ParseRef(s.String())
  297. }
  298. func ImageSpecFromRef(id image.Ref) ImageSpec {
  299. return ImageSpec(id.String())
  300. }