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.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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() 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 `ImageMap` of all relevant images
  167. var images ImageMap
  168. var singleRepo image.CanonicalName
  169. var err error
  170. switch s.ImageSpec {
  171. case ImageSpecLatest:
  172. images, err = collectUpdateImages(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. images, err = exactImages(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. latestImage, ok := images.LatestImage(currentImageID.Name, "*")
  204. if !ok {
  205. if currentImageID.CanonicalName() != singleRepo {
  206. ignoredOrSkipped = ReleaseStatusIgnored
  207. } else {
  208. ignoredOrSkipped = ReleaseStatusUnknown
  209. }
  210. continue
  211. }
  212. if currentImageID == latestImage.ID {
  213. ignoredOrSkipped = ReleaseStatusSkipped
  214. continue
  215. }
  216. // We want to update the image with respect to the form it
  217. // appears in the manifest, whereas what we have is the
  218. // canonical form.
  219. newImageID := currentImageID.WithNewTag(latestImage.ID.Tag)
  220. u.ManifestBytes, err = rc.Manifests().UpdateDefinition(u.ManifestBytes, container.Name, newImageID)
  221. if err != nil {
  222. return nil, err
  223. }
  224. containerUpdates = append(containerUpdates, ContainerUpdate{
  225. Container: container.Name,
  226. Current: currentImageID,
  227. Target: newImageID,
  228. })
  229. }
  230. switch {
  231. case len(containerUpdates) > 0:
  232. u.Updates = containerUpdates
  233. updates = append(updates, u)
  234. results[u.ResourceID] = ControllerResult{
  235. Status: ReleaseStatusSuccess,
  236. PerContainer: containerUpdates,
  237. }
  238. case ignoredOrSkipped == ReleaseStatusSkipped:
  239. results[u.ResourceID] = ControllerResult{
  240. Status: ReleaseStatusSkipped,
  241. Error: ImageUpToDate,
  242. }
  243. case ignoredOrSkipped == ReleaseStatusIgnored:
  244. results[u.ResourceID] = ControllerResult{
  245. Status: ReleaseStatusIgnored,
  246. Error: DoesNotUseImage,
  247. }
  248. case ignoredOrSkipped == ReleaseStatusUnknown:
  249. results[u.ResourceID] = ControllerResult{
  250. Status: ReleaseStatusSkipped,
  251. Error: ImageNotFound,
  252. }
  253. }
  254. }
  255. return updates, nil
  256. }
  257. type ResourceSpec string // ResourceID or "<all>"
  258. func ParseResourceSpec(s string) (ResourceSpec, error) {
  259. if s == string(ResourceSpecAll) {
  260. return ResourceSpecAll, nil
  261. }
  262. id, err := flux.ParseResourceID(s)
  263. if err != nil {
  264. return "", errors.Wrap(err, "invalid service spec")
  265. }
  266. return ResourceSpec(id.String()), nil
  267. }
  268. func MakeResourceSpec(id flux.ResourceID) ResourceSpec {
  269. return ResourceSpec(id.String())
  270. }
  271. func (s ResourceSpec) AsID() (flux.ResourceID, error) {
  272. return flux.ParseResourceID(string(s))
  273. }
  274. func (s ResourceSpec) String() string {
  275. return string(s)
  276. }
  277. // ImageSpec is an ImageID, or "<all latest>" (update all containers
  278. // to the latest available).
  279. type ImageSpec string
  280. func ParseImageSpec(s string) (ImageSpec, error) {
  281. if s == string(ImageSpecLatest) {
  282. return ImageSpecLatest, nil
  283. }
  284. id, err := image.ParseRef(s)
  285. if err != nil {
  286. return "", err
  287. }
  288. if id.Tag == "" {
  289. return "", errors.Wrap(image.ErrInvalidImageID, "blank tag (if you want latest, explicitly state the tag :latest)")
  290. }
  291. return ImageSpec(id.String()), err
  292. }
  293. func (s ImageSpec) String() string {
  294. return string(s)
  295. }
  296. func (s ImageSpec) AsRef() (image.Ref, error) {
  297. return image.ParseRef(s.String())
  298. }
  299. func ImageSpecFromRef(id image.Ref) ImageSpec {
  300. return ImageSpec(id.String())
  301. }