2
0

reflector.go 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cache
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "math/rand"
  20. "reflect"
  21. "strings"
  22. "sync"
  23. "time"
  24. apierrors "k8s.io/apimachinery/pkg/api/errors"
  25. "k8s.io/apimachinery/pkg/api/meta"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  28. metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
  29. "k8s.io/apimachinery/pkg/runtime"
  30. "k8s.io/apimachinery/pkg/runtime/schema"
  31. "k8s.io/apimachinery/pkg/util/naming"
  32. utilnet "k8s.io/apimachinery/pkg/util/net"
  33. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  34. "k8s.io/apimachinery/pkg/util/wait"
  35. "k8s.io/apimachinery/pkg/watch"
  36. clientfeatures "k8s.io/client-go/features"
  37. "k8s.io/client-go/tools/pager"
  38. "k8s.io/client-go/util/watchlist"
  39. "k8s.io/klog/v2"
  40. "k8s.io/utils/clock"
  41. "k8s.io/utils/ptr"
  42. "k8s.io/utils/trace"
  43. )
  44. const defaultExpectedTypeName = "<unspecified>"
  45. // We try to spread the load on apiserver by setting timeouts for
  46. // watch requests - it is random in [minWatchTimeout, 2*minWatchTimeout].
  47. var defaultMinWatchTimeout = 5 * time.Minute
  48. // ReflectorStore is the subset of cache.Store that the reflector uses
  49. type ReflectorStore interface {
  50. // Add adds the given object to the accumulator associated with the given object's key
  51. Add(obj interface{}) error
  52. // Update updates the given object in the accumulator associated with the given object's key
  53. Update(obj interface{}) error
  54. // Delete deletes the given object from the accumulator associated with the given object's key
  55. Delete(obj interface{}) error
  56. // Replace will delete the contents of the store, using instead the
  57. // given list. Store takes ownership of the list, you should not reference
  58. // it after calling this function.
  59. Replace([]interface{}, string) error
  60. // Resync is meaningless in the terms appearing here but has
  61. // meaning in some implementations that have non-trivial
  62. // additional behavior (e.g., DeltaFIFO).
  63. Resync() error
  64. }
  65. // TransformingStore is an optional interface that can be implemented by the provided store.
  66. // If implemented on the provided store reflector will use the same transformer in its internal stores.
  67. type TransformingStore interface {
  68. ReflectorStore
  69. Transformer() TransformFunc
  70. }
  71. // Reflector watches a specified resource and causes all changes to be reflected in the given store.
  72. type Reflector struct {
  73. // name identifies this reflector. By default, it will be a file:line if possible.
  74. name string
  75. // The name of the type we expect to place in the store. The name
  76. // will be the stringification of expectedGVK if provided, and the
  77. // stringification of expectedType otherwise. It is for display
  78. // only, and should not be used for parsing or comparison.
  79. typeDescription string
  80. // An example object of the type we expect to place in the store.
  81. // Only the type needs to be right, except that when that is
  82. // `unstructured.Unstructured` the object's `"apiVersion"` and
  83. // `"kind"` must also be right.
  84. expectedType reflect.Type
  85. // The GVK of the object we expect to place in the store if unstructured.
  86. expectedGVK *schema.GroupVersionKind
  87. // The destination to sync up with the watch source
  88. store ReflectorStore
  89. // listerWatcher is used to perform lists and watches.
  90. listerWatcher ListerWatcherWithContext
  91. // backoff manages backoff of ListWatch
  92. backoffManager wait.BackoffManager
  93. resyncPeriod time.Duration
  94. // minWatchTimeout defines the minimum timeout for watch requests.
  95. minWatchTimeout time.Duration
  96. // clock allows tests to manipulate time
  97. clock clock.Clock
  98. // paginatedResult defines whether pagination should be forced for list calls.
  99. // It is set based on the result of the initial list call.
  100. paginatedResult bool
  101. // lastSyncResourceVersion is the resource version token last
  102. // observed when doing a sync with the underlying store
  103. // it is thread safe, but not synchronized with the underlying store
  104. lastSyncResourceVersion string
  105. // isLastSyncResourceVersionUnavailable is true if the previous list or watch request with
  106. // lastSyncResourceVersion failed with an "expired" or "too large resource version" error.
  107. isLastSyncResourceVersionUnavailable bool
  108. // lastSyncResourceVersionMutex guards read/write access to lastSyncResourceVersion
  109. lastSyncResourceVersionMutex sync.RWMutex
  110. // Called whenever the ListAndWatch drops the connection with an error.
  111. watchErrorHandler WatchErrorHandlerWithContext
  112. // WatchListPageSize is the requested chunk size of initial and resync watch lists.
  113. // If unset, for consistent reads (RV="") or reads that opt-into arbitrarily old data
  114. // (RV="0") it will default to pager.PageSize, for the rest (RV != "" && RV != "0")
  115. // it will turn off pagination to allow serving them from watch cache.
  116. // NOTE: It should be used carefully as paginated lists are always served directly from
  117. // etcd, which is significantly less efficient and may lead to serious performance and
  118. // scalability problems.
  119. WatchListPageSize int64
  120. // ShouldResync is invoked periodically and whenever it returns `true` the Store's Resync operation is invoked
  121. ShouldResync func() bool
  122. // MaxInternalErrorRetryDuration defines how long we should retry internal errors returned by watch.
  123. MaxInternalErrorRetryDuration time.Duration
  124. // useWatchList if turned on instructs the reflector to open a stream to bring data from the API server.
  125. // Streaming has the primary advantage of using fewer server's resources to fetch data.
  126. //
  127. // The old behaviour establishes a LIST request which gets data in chunks.
  128. // Paginated list is less efficient and depending on the actual size of objects
  129. // might result in an increased memory consumption of the APIServer.
  130. //
  131. // See https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/3157-watch-list#design-details
  132. useWatchList bool
  133. }
  134. func (r *Reflector) Name() string {
  135. return r.name
  136. }
  137. func (r *Reflector) TypeDescription() string {
  138. return r.typeDescription
  139. }
  140. // ResourceVersionUpdater is an interface that allows store implementation to
  141. // track the current resource version of the reflector. This is especially
  142. // important if storage bookmarks are enabled.
  143. type ResourceVersionUpdater interface {
  144. // UpdateResourceVersion is called each time current resource version of the reflector
  145. // is updated.
  146. UpdateResourceVersion(resourceVersion string)
  147. }
  148. // The WatchErrorHandler is called whenever ListAndWatch drops the
  149. // connection with an error. After calling this handler, the informer
  150. // will backoff and retry.
  151. //
  152. // The default implementation looks at the error type and tries to log
  153. // the error message at an appropriate level.
  154. //
  155. // Implementations of this handler may display the error message in other
  156. // ways. Implementations should return quickly - any expensive processing
  157. // should be offloaded.
  158. type WatchErrorHandler func(r *Reflector, err error)
  159. // The WatchErrorHandler is called whenever ListAndWatch drops the
  160. // connection with an error. After calling this handler, the informer
  161. // will backoff and retry.
  162. //
  163. // The default implementation looks at the error type and tries to log
  164. // the error message at an appropriate level.
  165. //
  166. // Implementations of this handler may display the error message in other
  167. // ways. Implementations should return quickly - any expensive processing
  168. // should be offloaded.
  169. type WatchErrorHandlerWithContext func(ctx context.Context, r *Reflector, err error)
  170. // DefaultWatchErrorHandler is the default implementation of WatchErrorHandlerWithContext.
  171. func DefaultWatchErrorHandler(ctx context.Context, r *Reflector, err error) {
  172. switch {
  173. case isExpiredError(err):
  174. // Don't set LastSyncResourceVersionUnavailable - LIST call with ResourceVersion=RV already
  175. // has a semantic that it returns data at least as fresh as provided RV.
  176. // So first try to LIST with setting RV to resource version of last observed object.
  177. klog.FromContext(ctx).V(4).Info("Watch closed", "reflector", r.name, "type", r.typeDescription, "err", err)
  178. case err == io.EOF:
  179. // watch closed normally
  180. case err == io.ErrUnexpectedEOF:
  181. klog.FromContext(ctx).V(1).Info("Watch closed with unexpected EOF", "reflector", r.name, "type", r.typeDescription, "err", err)
  182. default:
  183. utilruntime.HandleErrorWithContext(ctx, err, "Failed to watch", "reflector", r.name, "type", r.typeDescription)
  184. }
  185. }
  186. // NewNamespaceKeyedIndexerAndReflector creates an Indexer and a Reflector
  187. // The indexer is configured to key on namespace
  188. func NewNamespaceKeyedIndexerAndReflector(lw ListerWatcher, expectedType interface{}, resyncPeriod time.Duration) (indexer Indexer, reflector *Reflector) {
  189. indexer = NewIndexer(MetaNamespaceKeyFunc, Indexers{NamespaceIndex: MetaNamespaceIndexFunc})
  190. reflector = NewReflector(lw, expectedType, indexer, resyncPeriod)
  191. return indexer, reflector
  192. }
  193. // NewReflector creates a new Reflector with its name defaulted to the closest source_file.go:line in the call stack
  194. // that is outside this package. See NewReflectorWithOptions for further information.
  195. func NewReflector(lw ListerWatcher, expectedType interface{}, store ReflectorStore, resyncPeriod time.Duration) *Reflector {
  196. return NewReflectorWithOptions(lw, expectedType, store, ReflectorOptions{ResyncPeriod: resyncPeriod})
  197. }
  198. // NewNamedReflector creates a new Reflector with the specified name. See NewReflectorWithOptions for further
  199. // information.
  200. func NewNamedReflector(name string, lw ListerWatcher, expectedType interface{}, store ReflectorStore, resyncPeriod time.Duration) *Reflector {
  201. return NewReflectorWithOptions(lw, expectedType, store, ReflectorOptions{Name: name, ResyncPeriod: resyncPeriod})
  202. }
  203. // ReflectorOptions configures a Reflector.
  204. type ReflectorOptions struct {
  205. // Name is the Reflector's name. If unset/unspecified, the name defaults to the closest source_file.go:line
  206. // in the call stack that is outside this package.
  207. Name string
  208. // TypeDescription is the Reflector's type description. If unset/unspecified, the type description is defaulted
  209. // using the following rules: if the expectedType passed to NewReflectorWithOptions was nil, the type description is
  210. // "<unspecified>". If the expectedType is an instance of *unstructured.Unstructured and its apiVersion and kind fields
  211. // are set, the type description is the string encoding of those. Otherwise, the type description is set to the
  212. // go type of expectedType..
  213. TypeDescription string
  214. // ResyncPeriod is the Reflector's resync period. If unset/unspecified, the resync period defaults to 0
  215. // (do not resync).
  216. ResyncPeriod time.Duration
  217. // MinWatchTimeout, if non-zero, defines the minimum timeout for watch requests send to kube-apiserver.
  218. // However, values lower than 5m will not be honored to avoid negative performance impact on controlplane.
  219. MinWatchTimeout time.Duration
  220. // Clock allows tests to control time. If unset defaults to clock.RealClock{}
  221. Clock clock.Clock
  222. }
  223. // NewReflectorWithOptions creates a new Reflector object which will keep the
  224. // given store up to date with the server's contents for the given
  225. // resource. Reflector promises to only put things in the store that
  226. // have the type of expectedType, unless expectedType is nil. If
  227. // resyncPeriod is non-zero, then the reflector will periodically
  228. // consult its ShouldResync function to determine whether to invoke
  229. // the Store's Resync operation; `ShouldResync==nil` means always
  230. // "yes". This enables you to use reflectors to periodically process
  231. // everything as well as incrementally processing the things that
  232. // change.
  233. func NewReflectorWithOptions(lw ListerWatcher, expectedType interface{}, store ReflectorStore, options ReflectorOptions) *Reflector {
  234. reflectorClock := options.Clock
  235. if reflectorClock == nil {
  236. reflectorClock = clock.RealClock{}
  237. }
  238. minWatchTimeout := defaultMinWatchTimeout
  239. if options.MinWatchTimeout > defaultMinWatchTimeout {
  240. minWatchTimeout = options.MinWatchTimeout
  241. }
  242. r := &Reflector{
  243. name: options.Name,
  244. resyncPeriod: options.ResyncPeriod,
  245. minWatchTimeout: minWatchTimeout,
  246. typeDescription: options.TypeDescription,
  247. listerWatcher: ToListerWatcherWithContext(lw),
  248. store: store,
  249. // We used to make the call every 1sec (1 QPS), the goal here is to achieve ~98% traffic reduction when
  250. // API server is not healthy. With these parameters, backoff will stop at [30,60) sec interval which is
  251. // 0.22 QPS. If we don't backoff for 2min, assume API server is healthy and we reset the backoff.
  252. backoffManager: wait.NewExponentialBackoffManager(800*time.Millisecond, 30*time.Second, 2*time.Minute, 2.0, 1.0, reflectorClock),
  253. clock: reflectorClock,
  254. watchErrorHandler: WatchErrorHandlerWithContext(DefaultWatchErrorHandler),
  255. expectedType: reflect.TypeOf(expectedType),
  256. }
  257. if r.name == "" {
  258. r.name = naming.GetNameFromCallsite(internalPackages...)
  259. }
  260. if r.typeDescription == "" {
  261. r.typeDescription = getTypeDescriptionFromObject(expectedType)
  262. }
  263. if r.expectedGVK == nil {
  264. r.expectedGVK = getExpectedGVKFromObject(expectedType)
  265. }
  266. r.useWatchList = clientfeatures.FeatureGates().Enabled(clientfeatures.WatchListClient)
  267. if r.useWatchList && watchlist.DoesClientNotSupportWatchListSemantics(lw) {
  268. // Using klog.TODO() here because switching to a caller-provided contextual logger
  269. // would require an API change and updating all existing call sites.
  270. klog.TODO().V(2).Info(
  271. "The provided ListWatcher doesn't support WatchList semantics. The feature will be disabled. If you are using a custom client, check the documentation of watchlist.DoesClientNotSupportWatchListSemantics() method",
  272. "listWatcherType", fmt.Sprintf("%T", lw),
  273. "feature", clientfeatures.WatchListClient,
  274. )
  275. r.useWatchList = false
  276. }
  277. return r
  278. }
  279. func getTypeDescriptionFromObject(expectedType interface{}) string {
  280. if expectedType == nil {
  281. return defaultExpectedTypeName
  282. }
  283. reflectDescription := reflect.TypeOf(expectedType).String()
  284. obj, ok := expectedType.(*unstructured.Unstructured)
  285. if !ok {
  286. return reflectDescription
  287. }
  288. gvk := obj.GroupVersionKind()
  289. if gvk.Empty() {
  290. return reflectDescription
  291. }
  292. return gvk.String()
  293. }
  294. func getExpectedGVKFromObject(expectedType interface{}) *schema.GroupVersionKind {
  295. obj, ok := expectedType.(*unstructured.Unstructured)
  296. if !ok {
  297. return nil
  298. }
  299. gvk := obj.GroupVersionKind()
  300. if gvk.Empty() {
  301. return nil
  302. }
  303. return &gvk
  304. }
  305. // internalPackages are packages that ignored when creating a default reflector name. These packages are in the common
  306. // call chains to NewReflector, so they'd be low entropy names for reflectors
  307. var internalPackages = []string{"client-go/tools/cache/"}
  308. // Run repeatedly uses the reflector's ListAndWatch to fetch all the
  309. // objects and subsequent deltas.
  310. // Run will exit when stopCh is closed.
  311. //
  312. // Contextual logging: RunWithContext should be used instead of Run in code which supports contextual logging.
  313. func (r *Reflector) Run(stopCh <-chan struct{}) {
  314. r.RunWithContext(wait.ContextForChannel(stopCh))
  315. }
  316. // RunWithContext repeatedly uses the reflector's ListAndWatch to fetch all the
  317. // objects and subsequent deltas.
  318. // Run will exit when the context is canceled.
  319. func (r *Reflector) RunWithContext(ctx context.Context) {
  320. logger := klog.FromContext(ctx)
  321. logger.V(3).Info("Starting reflector", "type", r.typeDescription, "resyncPeriod", r.resyncPeriod, "reflector", r.name)
  322. wait.BackoffUntil(func() {
  323. if err := r.ListAndWatchWithContext(ctx); err != nil {
  324. r.watchErrorHandler(ctx, r, err)
  325. }
  326. }, r.backoffManager, true, ctx.Done())
  327. logger.V(3).Info("Stopping reflector", "type", r.typeDescription, "resyncPeriod", r.resyncPeriod, "reflector", r.name)
  328. }
  329. var (
  330. // Used to indicate that watching stopped because of a signal from the stop
  331. // channel passed in from a client of the reflector.
  332. errorStopRequested = errors.New("stop requested")
  333. )
  334. // resyncChan returns a channel which will receive something when a resync is
  335. // required, and a cleanup function.
  336. func (r *Reflector) resyncChan() (<-chan time.Time, func() bool) {
  337. if r.resyncPeriod == 0 {
  338. // nothing will ever be sent down this channel
  339. return nil, func() bool { return false }
  340. }
  341. // The cleanup function is required: imagine the scenario where watches
  342. // always fail so we end up listing frequently. Then, if we don't
  343. // manually stop the timer, we could end up with many timers active
  344. // concurrently.
  345. t := r.clock.NewTimer(r.resyncPeriod)
  346. return t.C(), t.Stop
  347. }
  348. // ListAndWatch first lists all items and get the resource version at the moment of call,
  349. // and then use the resource version to watch.
  350. // It returns error if ListAndWatch didn't even try to initialize watch.
  351. //
  352. // Contextual logging: ListAndWatchWithContext should be used instead of ListAndWatch in code which supports contextual logging.
  353. func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error {
  354. return r.ListAndWatchWithContext(wait.ContextForChannel(stopCh))
  355. }
  356. // ListAndWatchWithContext first lists all items and get the resource version at the moment of call,
  357. // and then use the resource version to watch.
  358. // It returns error if ListAndWatchWithContext didn't even try to initialize watch.
  359. func (r *Reflector) ListAndWatchWithContext(ctx context.Context) error {
  360. logger := klog.FromContext(ctx)
  361. logger.V(3).Info("Listing and watching", "type", r.typeDescription, "reflector", r.name)
  362. var err error
  363. var w watch.Interface
  364. fallbackToList := !r.useWatchList
  365. defer func() {
  366. if w != nil {
  367. w.Stop()
  368. }
  369. }()
  370. if r.useWatchList {
  371. w, err = r.watchList(ctx)
  372. if w == nil && err == nil {
  373. // stopCh was closed
  374. return nil
  375. }
  376. if err != nil {
  377. logger.V(4).Info(
  378. "Data couldn't be fetched in watchlist mode. Falling back to regular list. This is expected if watchlist is not supported or disabled in kube-apiserver.",
  379. "err", err,
  380. )
  381. fallbackToList = true
  382. // ensure that we won't accidentally pass some garbage down the watch.
  383. w = nil
  384. }
  385. }
  386. if fallbackToList {
  387. err = r.list(ctx)
  388. if err != nil {
  389. return err
  390. }
  391. }
  392. logger.V(2).Info("Caches populated", "type", r.typeDescription, "reflector", r.name)
  393. return r.watchWithResync(ctx, w)
  394. }
  395. // startResync periodically calls r.store.Resync() method.
  396. // Note that this method is blocking and should be
  397. // called in a separate goroutine.
  398. func (r *Reflector) startResync(ctx context.Context, resyncerrc chan error) {
  399. logger := klog.FromContext(ctx)
  400. resyncCh, cleanup := r.resyncChan()
  401. defer func() {
  402. cleanup() // Call the last one written into cleanup
  403. }()
  404. for {
  405. select {
  406. case <-resyncCh:
  407. case <-ctx.Done():
  408. return
  409. }
  410. if r.ShouldResync == nil || r.ShouldResync() {
  411. logger.V(4).Info("Forcing resync", "reflector", r.name)
  412. if err := r.store.Resync(); err != nil {
  413. resyncerrc <- err
  414. return
  415. }
  416. }
  417. cleanup()
  418. resyncCh, cleanup = r.resyncChan()
  419. }
  420. }
  421. // watchWithResync runs watch with startResync in the background.
  422. func (r *Reflector) watchWithResync(ctx context.Context, w watch.Interface) error {
  423. resyncerrc := make(chan error, 1)
  424. cancelCtx, cancel := context.WithCancel(ctx)
  425. // Waiting for completion of the goroutine is relevant for race detector.
  426. // Without this, there is a race between "this function returns + code
  427. // waiting for it" and "goroutine does something".
  428. var wg wait.Group
  429. defer func() {
  430. cancel()
  431. wg.Wait()
  432. }()
  433. wg.Start(func() {
  434. r.startResync(cancelCtx, resyncerrc)
  435. })
  436. return r.watch(ctx, w, resyncerrc)
  437. }
  438. // watch starts a watch request with the server, consumes watch events, and
  439. // restarts the watch until an exit scenario is reached.
  440. //
  441. // If a watch is provided, it will be used, otherwise another will be started.
  442. // If the watcher has started, it will always be stopped before returning.
  443. func (r *Reflector) watch(ctx context.Context, w watch.Interface, resyncerrc chan error) error {
  444. stopCh := ctx.Done()
  445. logger := klog.FromContext(ctx)
  446. var err error
  447. retry := NewRetryWithDeadline(r.MaxInternalErrorRetryDuration, time.Minute, apierrors.IsInternalError, r.clock)
  448. defer func() {
  449. if w != nil {
  450. w.Stop()
  451. }
  452. }()
  453. for {
  454. // give the stopCh a chance to stop the loop, even in case of continue statements further down on errors
  455. select {
  456. case <-stopCh:
  457. // we can only end up here when the stopCh
  458. // was closed after a successful watchlist or list request
  459. return nil
  460. default:
  461. }
  462. // start the clock before sending the request, since some proxies won't flush headers until after the first watch event is sent
  463. start := r.clock.Now()
  464. if w == nil {
  465. timeoutSeconds := int64(r.minWatchTimeout.Seconds() * (rand.Float64() + 1.0))
  466. options := metav1.ListOptions{
  467. ResourceVersion: r.LastSyncResourceVersion(),
  468. // We want to avoid situations of hanging watchers. Stop any watchers that do not
  469. // receive any events within the timeout window.
  470. TimeoutSeconds: &timeoutSeconds,
  471. // To reduce load on kube-apiserver on watch restarts, you may enable watch bookmarks.
  472. // Reflector doesn't assume bookmarks are returned at all (if the server do not support
  473. // watch bookmarks, it will ignore this field).
  474. AllowWatchBookmarks: true,
  475. }
  476. w, err = r.listerWatcher.WatchWithContext(ctx, options)
  477. if err != nil {
  478. if canRetry := isWatchErrorRetriable(err); canRetry {
  479. logger.V(4).Info("Watch failed - backing off", "reflector", r.name, "type", r.typeDescription, "err", err)
  480. select {
  481. case <-stopCh:
  482. return nil
  483. case <-r.backoffManager.Backoff().C():
  484. continue
  485. }
  486. }
  487. return err
  488. }
  489. }
  490. err = handleWatch(ctx, start, w, r.store, r.expectedType, r.expectedGVK, r.name, r.typeDescription, r.setLastSyncResourceVersion,
  491. r.clock, resyncerrc)
  492. // handleWatch always stops the watcher. So we don't need to here.
  493. // Just set it to nil to trigger a retry on the next loop.
  494. w = nil
  495. retry.After(err)
  496. if err != nil {
  497. if !errors.Is(err, errorStopRequested) {
  498. switch {
  499. case isExpiredError(err):
  500. // Don't set LastSyncResourceVersionUnavailable - LIST call with ResourceVersion=RV already
  501. // has a semantic that it returns data at least as fresh as provided RV.
  502. // So first try to LIST with setting RV to resource version of last observed object.
  503. logger.V(4).Info("Watch closed", "reflector", r.name, "type", r.typeDescription, "err", err)
  504. case apierrors.IsTooManyRequests(err):
  505. logger.V(2).Info("Watch returned 429 - backing off", "reflector", r.name, "type", r.typeDescription)
  506. select {
  507. case <-stopCh:
  508. return nil
  509. case <-r.backoffManager.Backoff().C():
  510. continue
  511. }
  512. case apierrors.IsInternalError(err) && retry.ShouldRetry():
  513. logger.V(2).Info("Retrying watch after internal error", "reflector", r.name, "type", r.typeDescription, "err", err)
  514. continue
  515. default:
  516. logger.Info("Warning: watch ended with error", "reflector", r.name, "type", r.typeDescription, "err", err)
  517. }
  518. }
  519. return nil
  520. }
  521. }
  522. }
  523. // list simply lists all items and records a resource version obtained from the server at the moment of the call.
  524. // the resource version can be used for further progress notification (aka. watch).
  525. func (r *Reflector) list(ctx context.Context) error {
  526. var resourceVersion string
  527. options := metav1.ListOptions{ResourceVersion: r.relistResourceVersion()}
  528. initTrace := trace.New("Reflector ListAndWatch", trace.Field{Key: "name", Value: r.name})
  529. defer initTrace.LogIfLong(10 * time.Second)
  530. var list runtime.Object
  531. var paginatedResult bool
  532. var err error
  533. listCh := make(chan struct{}, 1)
  534. panicCh := make(chan interface{}, 1)
  535. go func() {
  536. defer func() {
  537. if r := recover(); r != nil {
  538. panicCh <- r
  539. }
  540. }()
  541. // Attempt to gather list in chunks, if supported by listerWatcher, if not, the first
  542. // list request will return the full response.
  543. pager := pager.New(pager.SimplePageFunc(func(opts metav1.ListOptions) (runtime.Object, error) {
  544. return r.listerWatcher.ListWithContext(ctx, opts)
  545. }))
  546. switch {
  547. case r.WatchListPageSize != 0:
  548. pager.PageSize = r.WatchListPageSize
  549. case r.paginatedResult:
  550. // We got a paginated result initially. Assume this resource and server honor
  551. // paging requests (i.e. watch cache is probably disabled) and leave the default
  552. // pager size set.
  553. case options.ResourceVersion != "" && options.ResourceVersion != "0":
  554. // User didn't explicitly request pagination.
  555. //
  556. // With ResourceVersion != "", we have a possibility to list from watch cache,
  557. // but we do that (for ResourceVersion != "0") only if Limit is unset.
  558. // To avoid thundering herd on etcd (e.g. on master upgrades), we explicitly
  559. // switch off pagination to force listing from watch cache (if enabled).
  560. // With the existing semantic of RV (result is at least as fresh as provided RV),
  561. // this is correct and doesn't lead to going back in time.
  562. //
  563. // We also don't turn off pagination for ResourceVersion="0", since watch cache
  564. // is ignoring Limit in that case anyway, and if watch cache is not enabled
  565. // we don't introduce regression.
  566. pager.PageSize = 0
  567. }
  568. list, paginatedResult, err = pager.ListWithAlloc(context.Background(), options)
  569. if isExpiredError(err) || isTooLargeResourceVersionError(err) {
  570. r.setIsLastSyncResourceVersionUnavailable(true)
  571. // Retry immediately if the resource version used to list is unavailable.
  572. // The pager already falls back to full list if paginated list calls fail due to an "Expired" error on
  573. // continuation pages, but the pager might not be enabled, the full list might fail because the
  574. // resource version it is listing at is expired or the cache may not yet be synced to the provided
  575. // resource version. So we need to fallback to resourceVersion="" in all to recover and ensure
  576. // the reflector makes forward progress.
  577. list, paginatedResult, err = pager.ListWithAlloc(context.Background(), metav1.ListOptions{ResourceVersion: r.relistResourceVersion()})
  578. }
  579. close(listCh)
  580. }()
  581. select {
  582. case <-ctx.Done():
  583. return nil
  584. case r := <-panicCh:
  585. panic(r)
  586. case <-listCh:
  587. }
  588. initTrace.Step("Objects listed", trace.Field{Key: "error", Value: err})
  589. if err != nil {
  590. return fmt.Errorf("failed to list %v: %w", r.typeDescription, err)
  591. }
  592. // We check if the list was paginated and if so set the paginatedResult based on that.
  593. // However, we want to do that only for the initial list (which is the only case
  594. // when we set ResourceVersion="0"). The reasoning behind it is that later, in some
  595. // situations we may force listing directly from etcd (by setting ResourceVersion="")
  596. // which will return paginated result, even if watch cache is enabled. However, in
  597. // that case, we still want to prefer sending requests to watch cache if possible.
  598. //
  599. // Paginated result returned for request with ResourceVersion="0" mean that watch
  600. // cache is disabled and there are a lot of objects of a given type. In such case,
  601. // there is no need to prefer listing from watch cache.
  602. if options.ResourceVersion == "0" && paginatedResult {
  603. r.paginatedResult = true
  604. }
  605. r.setIsLastSyncResourceVersionUnavailable(false) // list was successful
  606. listMetaInterface, err := meta.ListAccessor(list)
  607. if err != nil {
  608. return fmt.Errorf("unable to understand list result %#v: %v", list, err)
  609. }
  610. resourceVersion = listMetaInterface.GetResourceVersion()
  611. initTrace.Step("Resource version extracted")
  612. items, err := meta.ExtractListWithAlloc(list)
  613. if err != nil {
  614. return fmt.Errorf("unable to understand list result %#v (%v)", list, err)
  615. }
  616. initTrace.Step("Objects extracted")
  617. if err := r.syncWith(items, resourceVersion); err != nil {
  618. return fmt.Errorf("unable to sync list result: %v", err)
  619. }
  620. initTrace.Step("SyncWith done")
  621. r.setLastSyncResourceVersion(resourceVersion)
  622. initTrace.Step("Resource version updated")
  623. return nil
  624. }
  625. // watchList establishes a stream to get a consistent snapshot of data
  626. // from the server as described in https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/3157-watch-list#proposal
  627. //
  628. // case 1: start at Most Recent (RV="", ResourceVersionMatch=ResourceVersionMatchNotOlderThan)
  629. // Establishes a consistent stream with the server.
  630. // That means the returned data is consistent, as if, served directly from etcd via a quorum read.
  631. // It begins with synthetic "Added" events of all resources up to the most recent ResourceVersion.
  632. // It ends with a synthetic "Bookmark" event containing the most recent ResourceVersion.
  633. // After receiving a "Bookmark" event the reflector is considered to be synchronized.
  634. // It replaces its internal store with the collected items and
  635. // reuses the current watch requests for getting further events.
  636. //
  637. // case 2: start at Exact (RV>"0", ResourceVersionMatch=ResourceVersionMatchNotOlderThan)
  638. // Establishes a stream with the server at the provided resource version.
  639. // To establish the initial state the server begins with synthetic "Added" events.
  640. // It ends with a synthetic "Bookmark" event containing the provided or newer resource version.
  641. // After receiving a "Bookmark" event the reflector is considered to be synchronized.
  642. // It replaces its internal store with the collected items and
  643. // reuses the current watch requests for getting further events.
  644. func (r *Reflector) watchList(ctx context.Context) (watch.Interface, error) {
  645. stopCh := ctx.Done()
  646. logger := klog.FromContext(ctx)
  647. var w watch.Interface
  648. var err error
  649. var temporaryStore Store
  650. var resourceVersion string
  651. // TODO(#115478): see if this function could be turned
  652. // into a method and see if error handling
  653. // could be unified with the r.watch method
  654. isErrorRetriableWithSideEffectsFn := func(err error) bool {
  655. if canRetry := isWatchErrorRetriable(err); canRetry {
  656. logger.V(2).Info("watch-list failed - backing off", "reflector", r.name, "type", r.typeDescription, "err", err)
  657. <-r.backoffManager.Backoff().C()
  658. return true
  659. }
  660. if isExpiredError(err) || isTooLargeResourceVersionError(err) {
  661. // we tried to re-establish a watch request but the provided RV
  662. // has either expired or it is greater than the server knows about.
  663. // In that case we reset the RV and
  664. // try to get a consistent snapshot from the watch cache (case 1)
  665. r.setIsLastSyncResourceVersionUnavailable(true)
  666. return true
  667. }
  668. return false
  669. }
  670. var transformer TransformFunc
  671. storeOpts := []StoreOption{}
  672. if tr, ok := r.store.(TransformingStore); ok && tr.Transformer() != nil {
  673. transformer = tr.Transformer()
  674. storeOpts = append(storeOpts, WithTransformer(transformer))
  675. }
  676. initTrace := trace.New("Reflector WatchList", trace.Field{Key: "name", Value: r.name})
  677. defer initTrace.LogIfLong(10 * time.Second)
  678. for {
  679. select {
  680. case <-stopCh:
  681. return nil, nil
  682. default:
  683. }
  684. resourceVersion = ""
  685. lastKnownRV := r.rewatchResourceVersion()
  686. temporaryStore = NewStore(DeletionHandlingMetaNamespaceKeyFunc, storeOpts...)
  687. // TODO(#115478): large "list", slow clients, slow network, p&f
  688. // might slow down streaming and eventually fail.
  689. // maybe in such a case we should retry with an increased timeout?
  690. timeoutSeconds := int64(r.minWatchTimeout.Seconds() * (rand.Float64() + 1.0))
  691. options := metav1.ListOptions{
  692. ResourceVersion: lastKnownRV,
  693. AllowWatchBookmarks: true,
  694. SendInitialEvents: ptr.To(true),
  695. ResourceVersionMatch: metav1.ResourceVersionMatchNotOlderThan,
  696. TimeoutSeconds: &timeoutSeconds,
  697. }
  698. start := r.clock.Now()
  699. w, err = r.listerWatcher.WatchWithContext(ctx, options)
  700. if err != nil {
  701. if isErrorRetriableWithSideEffectsFn(err) {
  702. continue
  703. }
  704. return nil, err
  705. }
  706. watchListBookmarkReceived, err := handleListWatch(ctx, start, w, temporaryStore, r.expectedType, r.expectedGVK, r.name, r.typeDescription,
  707. func(rv string) { resourceVersion = rv },
  708. r.clock, make(chan error))
  709. if err != nil {
  710. w.Stop() // stop and retry with clean state
  711. if errors.Is(err, errorStopRequested) {
  712. return nil, nil
  713. }
  714. if isErrorRetriableWithSideEffectsFn(err) {
  715. continue
  716. }
  717. return nil, err
  718. }
  719. if watchListBookmarkReceived {
  720. break
  721. }
  722. }
  723. // We successfully got initial state from watch-list confirmed by the
  724. // "k8s.io/initial-events-end" bookmark.
  725. initTrace.Step("Objects streamed", trace.Field{Key: "count", Value: len(temporaryStore.List())})
  726. r.setIsLastSyncResourceVersionUnavailable(false)
  727. // we utilize the temporaryStore to ensure independence from the current store implementation.
  728. // as of today, the store is implemented as a queue and will be drained by the higher-level
  729. // component as soon as it finishes replacing the content.
  730. checkWatchListDataConsistencyIfRequested(ctx, r.name, resourceVersion, r.listerWatcher.ListWithContext, transformer, temporaryStore.List)
  731. if err := r.store.Replace(temporaryStore.List(), resourceVersion); err != nil {
  732. return nil, fmt.Errorf("unable to sync watch-list result: %w", err)
  733. }
  734. initTrace.Step("SyncWith done")
  735. r.setLastSyncResourceVersion(resourceVersion)
  736. return w, nil
  737. }
  738. // syncWith replaces the store's items with the given list.
  739. func (r *Reflector) syncWith(items []runtime.Object, resourceVersion string) error {
  740. found := make([]interface{}, 0, len(items))
  741. for _, item := range items {
  742. found = append(found, item)
  743. }
  744. return r.store.Replace(found, resourceVersion)
  745. }
  746. // handleListWatch consumes events from w, updates the Store, and records the
  747. // last seen ResourceVersion, to allow continuing from that ResourceVersion on
  748. // retry. If successful, the watcher will be left open after receiving the
  749. // initial set of objects, to allow watching for future events.
  750. func handleListWatch(
  751. ctx context.Context,
  752. start time.Time,
  753. w watch.Interface,
  754. store Store,
  755. expectedType reflect.Type,
  756. expectedGVK *schema.GroupVersionKind,
  757. name string,
  758. expectedTypeName string,
  759. setLastSyncResourceVersion func(string),
  760. clock clock.Clock,
  761. errCh chan error,
  762. ) (bool, error) {
  763. exitOnWatchListBookmarkReceived := true
  764. return handleAnyWatch(ctx, start, w, store, expectedType, expectedGVK, name, expectedTypeName,
  765. setLastSyncResourceVersion, exitOnWatchListBookmarkReceived, clock, errCh)
  766. }
  767. // handleListWatch consumes events from w, updates the Store, and records the
  768. // last seen ResourceVersion, to allow continuing from that ResourceVersion on
  769. // retry. The watcher will always be stopped on exit.
  770. func handleWatch(
  771. ctx context.Context,
  772. start time.Time,
  773. w watch.Interface,
  774. store ReflectorStore,
  775. expectedType reflect.Type,
  776. expectedGVK *schema.GroupVersionKind,
  777. name string,
  778. expectedTypeName string,
  779. setLastSyncResourceVersion func(string),
  780. clock clock.Clock,
  781. errCh chan error,
  782. ) error {
  783. exitOnWatchListBookmarkReceived := false
  784. _, err := handleAnyWatch(ctx, start, w, store, expectedType, expectedGVK, name, expectedTypeName,
  785. setLastSyncResourceVersion, exitOnWatchListBookmarkReceived, clock, errCh)
  786. return err
  787. }
  788. // handleAnyWatch consumes events from w, updates the Store, and records the last
  789. // seen ResourceVersion, to allow continuing from that ResourceVersion on retry.
  790. // If exitOnWatchListBookmarkReceived is true, the watch events will be consumed
  791. // until a bookmark event is received with the WatchList annotation present.
  792. // Returns true (watchListBookmarkReceived) if the WatchList bookmark was
  793. // received, even if exitOnWatchListBookmarkReceived is false.
  794. // The watcher will always be stopped, unless exitOnWatchListBookmarkReceived is
  795. // true and watchListBookmarkReceived is true. This allows the same watch stream
  796. // to be re-used by the caller to continue watching for new events.
  797. func handleAnyWatch(
  798. ctx context.Context,
  799. start time.Time,
  800. w watch.Interface,
  801. store ReflectorStore,
  802. expectedType reflect.Type,
  803. expectedGVK *schema.GroupVersionKind,
  804. name string,
  805. expectedTypeName string,
  806. setLastSyncResourceVersion func(string),
  807. exitOnWatchListBookmarkReceived bool,
  808. clock clock.Clock,
  809. errCh chan error,
  810. ) (bool, error) {
  811. watchListBookmarkReceived := false
  812. eventCount := 0
  813. logger := klog.FromContext(ctx)
  814. initialEventsEndBookmarkWarningTicker := newInitialEventsEndBookmarkTicker(logger, name, clock, start, exitOnWatchListBookmarkReceived)
  815. defer initialEventsEndBookmarkWarningTicker.Stop()
  816. stopWatcher := true
  817. defer func() {
  818. if stopWatcher {
  819. w.Stop()
  820. }
  821. }()
  822. loop:
  823. for {
  824. select {
  825. case <-ctx.Done():
  826. return watchListBookmarkReceived, errorStopRequested
  827. case err := <-errCh:
  828. return watchListBookmarkReceived, err
  829. case event, ok := <-w.ResultChan():
  830. if !ok {
  831. break loop
  832. }
  833. if event.Type == watch.Error {
  834. return watchListBookmarkReceived, apierrors.FromObject(event.Object)
  835. }
  836. if expectedType != nil {
  837. if e, a := expectedType, reflect.TypeOf(event.Object); e != a {
  838. utilruntime.HandleErrorWithContext(ctx, nil, "Unexpected watch event object type", "reflector", name, "expectedType", e, "actualType", a)
  839. continue
  840. }
  841. }
  842. if expectedGVK != nil {
  843. if e, a := *expectedGVK, event.Object.GetObjectKind().GroupVersionKind(); e != a {
  844. utilruntime.HandleErrorWithContext(ctx, nil, "Unexpected watch event object gvk", "reflector", name, "expectedGVK", e, "actualGVK", a)
  845. continue
  846. }
  847. }
  848. // For now, let’s block unsupported Table
  849. // resources for watchlist only
  850. // see #132926 for more info
  851. if exitOnWatchListBookmarkReceived {
  852. if unsupportedGVK := isUnsupportedTableObject(event.Object); unsupportedGVK {
  853. utilruntime.HandleErrorWithContext(ctx, nil, "Unsupported watch event object gvk", "reflector", name, "actualGVK", event.Object.GetObjectKind().GroupVersionKind())
  854. continue
  855. }
  856. }
  857. meta, err := meta.Accessor(event.Object)
  858. if err != nil {
  859. utilruntime.HandleErrorWithContext(ctx, err, "Unable to understand watch event", "reflector", name, "event", event)
  860. continue
  861. }
  862. resourceVersion := meta.GetResourceVersion()
  863. switch event.Type {
  864. case watch.Added:
  865. err := store.Add(event.Object)
  866. if err != nil {
  867. utilruntime.HandleErrorWithContext(ctx, err, "Unable to add watch event object to store", "reflector", name, "object", event.Object)
  868. }
  869. case watch.Modified:
  870. err := store.Update(event.Object)
  871. if err != nil {
  872. utilruntime.HandleErrorWithContext(ctx, err, "Unable to update watch event object to store", "reflector", name, "object", event.Object)
  873. }
  874. case watch.Deleted:
  875. // TODO: Will any consumers need access to the "last known
  876. // state", which is passed in event.Object? If so, may need
  877. // to change this.
  878. err := store.Delete(event.Object)
  879. if err != nil {
  880. utilruntime.HandleErrorWithContext(ctx, err, "Unable to delete watch event object from store", "reflector", name, "object", event.Object)
  881. }
  882. case watch.Bookmark:
  883. // A `Bookmark` means watch has synced here, just update the resourceVersion
  884. if meta.GetAnnotations()[metav1.InitialEventsAnnotationKey] == "true" {
  885. watchListBookmarkReceived = true
  886. }
  887. default:
  888. utilruntime.HandleErrorWithContext(ctx, err, "Unknown watch event", "reflector", name, "event", event)
  889. }
  890. setLastSyncResourceVersion(resourceVersion)
  891. if rvu, ok := store.(ResourceVersionUpdater); ok {
  892. rvu.UpdateResourceVersion(resourceVersion)
  893. }
  894. eventCount++
  895. if exitOnWatchListBookmarkReceived && watchListBookmarkReceived {
  896. stopWatcher = false
  897. watchDuration := clock.Since(start)
  898. klog.FromContext(ctx).V(4).Info("Exiting watch because received the bookmark that marks the end of initial events stream", "reflector", name, "totalItems", eventCount, "duration", watchDuration)
  899. return watchListBookmarkReceived, nil
  900. }
  901. initialEventsEndBookmarkWarningTicker.observeLastEventTimeStamp(clock.Now())
  902. case <-initialEventsEndBookmarkWarningTicker.C():
  903. initialEventsEndBookmarkWarningTicker.warnIfExpired()
  904. }
  905. }
  906. watchDuration := clock.Since(start)
  907. if watchDuration < 1*time.Second && eventCount == 0 {
  908. return watchListBookmarkReceived, &VeryShortWatchError{Name: name}
  909. }
  910. klog.FromContext(ctx).V(4).Info("Watch close", "reflector", name, "type", expectedTypeName, "totalItems", eventCount)
  911. return watchListBookmarkReceived, nil
  912. }
  913. // LastSyncResourceVersion is the resource version observed when last sync with the underlying store
  914. // The value returned is not synchronized with access to the underlying store and is not thread-safe
  915. func (r *Reflector) LastSyncResourceVersion() string {
  916. r.lastSyncResourceVersionMutex.RLock()
  917. defer r.lastSyncResourceVersionMutex.RUnlock()
  918. return r.lastSyncResourceVersion
  919. }
  920. func (r *Reflector) setLastSyncResourceVersion(v string) {
  921. r.lastSyncResourceVersionMutex.Lock()
  922. defer r.lastSyncResourceVersionMutex.Unlock()
  923. r.lastSyncResourceVersion = v
  924. }
  925. // relistResourceVersion determines the resource version the reflector should list or relist from.
  926. // Returns either the lastSyncResourceVersion so that this reflector will relist with a resource
  927. // versions no older than has already been observed in relist results or watch events, or, if the last relist resulted
  928. // in an HTTP 410 (Gone) status code, returns "" so that the relist will use the latest resource version available in
  929. // etcd via a quorum read.
  930. func (r *Reflector) relistResourceVersion() string {
  931. r.lastSyncResourceVersionMutex.RLock()
  932. defer r.lastSyncResourceVersionMutex.RUnlock()
  933. if r.isLastSyncResourceVersionUnavailable {
  934. // Since this reflector makes paginated list requests, and all paginated list requests skip the watch cache
  935. // if the lastSyncResourceVersion is unavailable, we set ResourceVersion="" and list again to re-establish reflector
  936. // to the latest available ResourceVersion, using a consistent read from etcd.
  937. return ""
  938. }
  939. if r.lastSyncResourceVersion == "" {
  940. // For performance reasons, initial list performed by reflector uses "0" as resource version to allow it to
  941. // be served from the watch cache if it is enabled.
  942. return "0"
  943. }
  944. return r.lastSyncResourceVersion
  945. }
  946. // rewatchResourceVersion determines the resource version the reflector should start streaming from.
  947. func (r *Reflector) rewatchResourceVersion() string {
  948. r.lastSyncResourceVersionMutex.RLock()
  949. defer r.lastSyncResourceVersionMutex.RUnlock()
  950. if r.isLastSyncResourceVersionUnavailable {
  951. // initial stream should return data at the most recent resource version.
  952. // the returned data must be consistent i.e. as if served from etcd via a quorum read
  953. return ""
  954. }
  955. return r.lastSyncResourceVersion
  956. }
  957. // setIsLastSyncResourceVersionUnavailable sets if the last list or watch request with lastSyncResourceVersion returned
  958. // "expired" or "too large resource version" error.
  959. func (r *Reflector) setIsLastSyncResourceVersionUnavailable(isUnavailable bool) {
  960. r.lastSyncResourceVersionMutex.Lock()
  961. defer r.lastSyncResourceVersionMutex.Unlock()
  962. r.isLastSyncResourceVersionUnavailable = isUnavailable
  963. }
  964. func isExpiredError(err error) bool {
  965. // In Kubernetes 1.17 and earlier, the api server returns both apierrors.StatusReasonExpired and
  966. // apierrors.StatusReasonGone for HTTP 410 (Gone) status code responses. In 1.18 the kube server is more consistent
  967. // and always returns apierrors.StatusReasonExpired. For backward compatibility we can only remove the apierrors.IsGone
  968. // check when we fully drop support for Kubernetes 1.17 servers from reflectors.
  969. return apierrors.IsResourceExpired(err) || apierrors.IsGone(err)
  970. }
  971. func isTooLargeResourceVersionError(err error) bool {
  972. if apierrors.HasStatusCause(err, metav1.CauseTypeResourceVersionTooLarge) {
  973. return true
  974. }
  975. // In Kubernetes 1.17.0-1.18.5, the api server doesn't set the error status cause to
  976. // metav1.CauseTypeResourceVersionTooLarge to indicate that the requested minimum resource
  977. // version is larger than the largest currently available resource version. To ensure backward
  978. // compatibility with these server versions we also need to detect the error based on the content
  979. // of the error message field.
  980. if !apierrors.IsTimeout(err) {
  981. return false
  982. }
  983. apierr, ok := err.(apierrors.APIStatus)
  984. if !ok || apierr == nil || apierr.Status().Details == nil {
  985. return false
  986. }
  987. for _, cause := range apierr.Status().Details.Causes {
  988. // Matches the message returned by api server 1.17.0-1.18.5 for this error condition
  989. if cause.Message == "Too large resource version" {
  990. return true
  991. }
  992. }
  993. // Matches the message returned by api server before 1.17.0
  994. if strings.Contains(apierr.Status().Message, "Too large resource version") {
  995. return true
  996. }
  997. return false
  998. }
  999. // isWatchErrorRetriable determines if it is safe to retry
  1000. // a watch error retrieved from the server.
  1001. func isWatchErrorRetriable(err error) bool {
  1002. // If this is "connection refused" error, it means that most likely apiserver is not responsive.
  1003. // It doesn't make sense to re-list all objects because most likely we will be able to restart
  1004. // watch where we ended.
  1005. // If that's the case begin exponentially backing off and resend watch request.
  1006. // Do the same for "429" errors.
  1007. if utilnet.IsConnectionRefused(err) || apierrors.IsTooManyRequests(err) {
  1008. return true
  1009. }
  1010. return false
  1011. }
  1012. // initialEventsEndBookmarkTicker a ticker that produces a warning if the bookmark event
  1013. // which marks the end of the watch stream, has not been received within the defined tick interval.
  1014. //
  1015. // Note:
  1016. // The methods exposed by this type are not thread-safe.
  1017. type initialEventsEndBookmarkTicker struct {
  1018. clock.Ticker
  1019. clock clock.Clock
  1020. name string
  1021. logger klog.Logger
  1022. watchStart time.Time
  1023. tickInterval time.Duration
  1024. lastEventObserveTime time.Time
  1025. }
  1026. // newInitialEventsEndBookmarkTicker returns a noop ticker if exitOnInitialEventsEndBookmarkRequested is false.
  1027. // Otherwise, it returns a ticker that exposes a method producing a warning if the bookmark event,
  1028. // which marks the end of the watch stream, has not been received within the defined tick interval.
  1029. //
  1030. // Note that the caller controls whether to call t.C() and t.Stop().
  1031. //
  1032. // In practice, the reflector exits the watchHandler as soon as the bookmark event is received and calls the t.C() method.
  1033. func newInitialEventsEndBookmarkTicker(logger klog.Logger, name string, c clock.Clock, watchStart time.Time, exitOnWatchListBookmarkReceived bool) *initialEventsEndBookmarkTicker {
  1034. return newInitialEventsEndBookmarkTickerInternal(logger, name, c, watchStart, 10*time.Second, exitOnWatchListBookmarkReceived)
  1035. }
  1036. func newInitialEventsEndBookmarkTickerInternal(logger klog.Logger, name string, c clock.Clock, watchStart time.Time, tickInterval time.Duration, exitOnWatchListBookmarkReceived bool) *initialEventsEndBookmarkTicker {
  1037. clockWithTicker, ok := c.(clock.WithTicker)
  1038. if !ok || !exitOnWatchListBookmarkReceived {
  1039. if exitOnWatchListBookmarkReceived {
  1040. logger.Info("Warning: clock does not support WithTicker interface but exitOnInitialEventsEndBookmark was requested")
  1041. }
  1042. return &initialEventsEndBookmarkTicker{
  1043. Ticker: &noopTicker{},
  1044. }
  1045. }
  1046. return &initialEventsEndBookmarkTicker{
  1047. Ticker: clockWithTicker.NewTicker(tickInterval),
  1048. clock: c,
  1049. name: name,
  1050. logger: logger,
  1051. watchStart: watchStart,
  1052. tickInterval: tickInterval,
  1053. }
  1054. }
  1055. func (t *initialEventsEndBookmarkTicker) observeLastEventTimeStamp(lastEventObserveTime time.Time) {
  1056. t.lastEventObserveTime = lastEventObserveTime
  1057. }
  1058. func (t *initialEventsEndBookmarkTicker) warnIfExpired() {
  1059. if err := t.produceWarningIfExpired(); err != nil {
  1060. t.logger.Info("Warning: event bookmark expired", "err", err)
  1061. }
  1062. }
  1063. // produceWarningIfExpired returns an error that represents a warning when
  1064. // the time elapsed since the last received event exceeds the tickInterval.
  1065. //
  1066. // Note that this method should be called when t.C() yields a value.
  1067. func (t *initialEventsEndBookmarkTicker) produceWarningIfExpired() error {
  1068. if _, ok := t.Ticker.(*noopTicker); ok {
  1069. return nil /*noop ticker*/
  1070. }
  1071. if t.lastEventObserveTime.IsZero() {
  1072. return fmt.Errorf("%s: awaiting required bookmark event for initial events stream, no events received for %v", t.name, t.clock.Since(t.watchStart))
  1073. }
  1074. elapsedTime := t.clock.Now().Sub(t.lastEventObserveTime)
  1075. hasBookmarkTimerExpired := elapsedTime >= t.tickInterval
  1076. if !hasBookmarkTimerExpired {
  1077. return nil
  1078. }
  1079. return fmt.Errorf("%s: hasn't received required bookmark event marking the end of initial events stream, received last event %v ago", t.name, elapsedTime)
  1080. }
  1081. var _ clock.Ticker = &noopTicker{}
  1082. // TODO(#115478): move to k8s/utils repo
  1083. type noopTicker struct{}
  1084. func (t *noopTicker) C() <-chan time.Time { return nil }
  1085. func (t *noopTicker) Stop() {}
  1086. // VeryShortWatchError is returned when the watch result channel is closed
  1087. // within one second, without having sent any events.
  1088. type VeryShortWatchError struct {
  1089. // Name of the Reflector
  1090. Name string
  1091. }
  1092. // Error implements the error interface
  1093. func (e *VeryShortWatchError) Error() string {
  1094. return fmt.Sprintf("very short watch: %s: Unexpected watch close - "+
  1095. "watch lasted less than a second and no items received", e.Name)
  1096. }
  1097. var unsupportedTableGVK = map[schema.GroupVersionKind]bool{
  1098. metav1beta1.SchemeGroupVersion.WithKind("Table"): true,
  1099. metav1.SchemeGroupVersion.WithKind("Table"): true,
  1100. }
  1101. // isUnsupportedTableObject checks whether the given runtime.Object
  1102. // is a "Table" object that belongs to a set of well-known unsupported GroupVersionKinds.
  1103. func isUnsupportedTableObject(rawObject runtime.Object) bool {
  1104. unstructuredObj, ok := rawObject.(*unstructured.Unstructured)
  1105. if !ok {
  1106. return false
  1107. }
  1108. if unstructuredObj.GetKind() != "Table" {
  1109. return false
  1110. }
  1111. return unsupportedTableGVK[rawObject.GetObjectKind().GroupVersionKind()]
  1112. }