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.go 9.1KB

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