kube_runtime/reflector/mod.rs
1//! Caches objects in memory
2
3mod dispatcher;
4mod object_ref;
5pub mod store;
6#[cfg(feature = "unstable-runtime-subscribe")] mod subscriber;
7
8pub use self::{
9 dispatcher::ReflectHandle,
10 object_ref::{Extra as ObjectRefExtra, Lookup, ObjectRef},
11};
12use crate::watcher;
13use async_stream::stream;
14use futures::{Stream, StreamExt};
15use std::hash::Hash;
16#[cfg(feature = "unstable-runtime-subscribe")] pub use store::store_shared;
17pub use store::{Store, store};
18
19/// Cache objects from a [`watcher()`] stream into a local [`Store`]
20///
21/// Observes the raw `Stream` of [`watcher::Event`] objects, and modifies the cache.
22/// It passes the raw [`watcher()`] stream through unmodified.
23///
24/// ## Usage
25/// Create a [`Store`] through e.g. [`store::store()`]. The `writer` part is not-cloneable,
26/// and must be moved into the reflector. The `reader` part is the [`Store`] interface
27/// that you can send to other parts of your program as state.
28///
29/// The cache contains the last-seen state of objects,
30/// which may lag slightly behind the actual state.
31///
32/// ## Example
33///
34/// Infinite watch of [`Node`](k8s_openapi::api::core::v1::Node) resources with a certain label.
35///
36/// The `reader` part being passed around to a webserver is omitted.
37/// For examples see [version-rs](https://github.com/kube-rs/version-rs) for integration with [axum](https://github.com/tokio-rs/axum),
38/// or [controller-rs](https://github.com/kube-rs/controller-rs) for the similar controller integration with [actix-web](https://actix.rs/).
39///
40/// ```no_run
41/// use std::future::ready;
42/// use k8s_openapi::api::core::v1::Node;
43/// use kube::runtime::{reflector, watcher, WatchStreamExt, watcher::Config};
44/// use futures::StreamExt;
45/// # use kube::api::Api;
46/// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
47/// # let client: kube::Client = todo!();
48///
49/// let nodes: Api<Node> = Api::all(client);
50/// let node_filter = Config::default().labels("kubernetes.io/arch=amd64");
51/// let (reader, writer) = reflector::store();
52///
53/// // Create the infinite reflector stream
54/// let rf = reflector(writer, watcher(nodes, node_filter));
55///
56/// // !!! pass reader to your webserver/manager as state !!!
57///
58/// // Poll the stream (needed to keep the store up-to-date)
59/// let infinite_watch = rf.applied_objects().for_each(|o| { ready(()) });
60/// infinite_watch.await;
61/// # Ok(())
62/// # }
63/// ```
64///
65///
66/// ## Memory Usage
67///
68/// A reflector often constitutes one of the biggest components of a controller's memory use.
69/// Given a ~2000 pods cluster, a reflector saving everything (including injected sidecars, managed fields)
70/// can quickly consume a couple of hundred megabytes or more, depending on how much of this you are storing.
71///
72/// While generally acceptable, there are techniques you can leverage to reduce the memory usage
73/// depending on your use case.
74///
75/// 1. Reflect a [`PartialObjectMeta<K>`](kube_client::core::PartialObjectMeta) stream rather than a stream of `K`
76///
77/// You can send in a [`metadata_watcher()`](crate::watcher::metadata_watcher()) for a type rather than a [`watcher()`],
78/// and this can drop your memory usage by more than a factor of two,
79/// depending on the size of `K`. 60% reduction seen for `Pod`. Usage is otherwise identical.
80///
81/// 2. Use `modify` the raw [`watcher::Event`] object stream to clear unneeded properties
82///
83/// For instance, managed fields typically constitutes around half the size of `ObjectMeta` and can often be dropped:
84///
85/// ```no_run
86/// # use futures::TryStreamExt;
87/// # use kube::{ResourceExt, Api, runtime::watcher};
88/// # let api: Api<k8s_openapi::api::core::v1::Node> = todo!();
89/// let stream = watcher(api, Default::default()).map_ok(|ev| {
90/// ev.modify(|pod| {
91/// pod.managed_fields_mut().clear();
92/// pod.annotations_mut().clear();
93/// pod.status = None;
94/// })
95/// });
96/// ```
97/// The `stream` can then be passed to `reflector` causing smaller objects to be written to its store.
98/// Note that you **cannot drop everything**; you minimally need the spec properties your app relies on.
99/// Additionally, only `labels`, `annotations` and `managed_fields` are safe to drop from `ObjectMeta`.
100///
101/// For more information check out: <https://kube.rs/controllers/optimization/> for graphs and techniques.
102///
103/// ## Stream sharing
104///
105/// `reflector()` as an interface may optionally create a stream that can be
106/// shared with other components to help with resource usage.
107///
108/// To share a stream, the `Writer<K>` consumed by `reflector()` must be
109/// created through an interface that allows a store to be subscribed on, such
110/// as [`store_shared()`]. When the store supports being subscribed on, it will
111/// broadcast an event to all active listeners after caching any object
112/// contained in the event.
113pub fn reflector<K, W>(mut writer: store::Writer<K>, stream: W) -> impl Stream<Item = W::Item>
114where
115 K: Lookup + Clone,
116 K::DynamicType: Eq + Hash + Clone,
117 W: Stream<Item = watcher::Result<watcher::Event<K>>>,
118{
119 let mut stream = Box::pin(stream);
120 stream! {
121 while let Some(event) = stream.next().await {
122 match event {
123 Ok(ev) => {
124 writer.apply_watcher_event(&ev);
125 writer.dispatch_event(&ev).await;
126 yield Ok(ev);
127 },
128 Err(ev) => yield Err(ev)
129 }
130 }
131 }
132}
133
134#[cfg(test)]
135mod tests {
136 use super::{ObjectRef, reflector, store};
137 use crate::watcher;
138 use futures::{StreamExt, TryStreamExt, stream};
139 use k8s_openapi::{api::core::v1::ConfigMap, apimachinery::pkg::apis::meta::v1::ObjectMeta};
140 use rand::{
141 RngExt,
142 distr::{Bernoulli, Uniform},
143 };
144 use std::collections::{BTreeMap, HashMap};
145
146 #[tokio::test]
147 async fn reflector_applied_should_add_object() {
148 let store_w = store::Writer::default();
149 let store = store_w.as_reader();
150 let cm = ConfigMap {
151 metadata: ObjectMeta {
152 name: Some("a".to_string()),
153 ..ObjectMeta::default()
154 },
155 ..ConfigMap::default()
156 };
157 reflector(store_w, stream::iter(vec![Ok(watcher::Event::Apply(cm.clone()))]))
158 .map(|_| ())
159 .collect::<()>()
160 .await;
161 assert_eq!(store.get(&ObjectRef::from_obj(&cm)).as_deref(), Some(&cm));
162 }
163
164 #[tokio::test]
165 async fn reflector_applied_should_update_object() {
166 let store_w = store::Writer::default();
167 let store = store_w.as_reader();
168 let cm = ConfigMap {
169 metadata: ObjectMeta {
170 name: Some("a".to_string()),
171 ..ObjectMeta::default()
172 },
173 ..ConfigMap::default()
174 };
175 let updated_cm = ConfigMap {
176 data: Some({
177 let mut data = BTreeMap::new();
178 data.insert("data".to_string(), "present!".to_string());
179 data
180 }),
181 ..cm.clone()
182 };
183 reflector(
184 store_w,
185 stream::iter(vec![
186 Ok(watcher::Event::Apply(cm.clone())),
187 Ok(watcher::Event::Apply(updated_cm.clone())),
188 ]),
189 )
190 .map(|_| ())
191 .collect::<()>()
192 .await;
193 assert_eq!(store.get(&ObjectRef::from_obj(&cm)).as_deref(), Some(&updated_cm));
194 }
195
196 #[tokio::test]
197 async fn reflector_deleted_should_remove_object() {
198 let store_w = store::Writer::default();
199 let store = store_w.as_reader();
200 let cm = ConfigMap {
201 metadata: ObjectMeta {
202 name: Some("a".to_string()),
203 ..ObjectMeta::default()
204 },
205 ..ConfigMap::default()
206 };
207 reflector(
208 store_w,
209 stream::iter(vec![
210 Ok(watcher::Event::Apply(cm.clone())),
211 Ok(watcher::Event::Delete(cm.clone())),
212 ]),
213 )
214 .map(|_| ())
215 .collect::<()>()
216 .await;
217 assert_eq!(store.get(&ObjectRef::from_obj(&cm)), None);
218 }
219
220 #[tokio::test]
221 async fn reflector_restarted_should_clear_objects() {
222 let store_w = store::Writer::default();
223 let store = store_w.as_reader();
224 let cm_a = ConfigMap {
225 metadata: ObjectMeta {
226 name: Some("a".to_string()),
227 ..ObjectMeta::default()
228 },
229 ..ConfigMap::default()
230 };
231 let cm_b = ConfigMap {
232 metadata: ObjectMeta {
233 name: Some("b".to_string()),
234 ..ObjectMeta::default()
235 },
236 ..ConfigMap::default()
237 };
238 reflector(
239 store_w,
240 stream::iter(vec![
241 Ok(watcher::Event::Apply(cm_a.clone())),
242 Ok(watcher::Event::Init),
243 Ok(watcher::Event::InitApply(cm_b.clone())),
244 Ok(watcher::Event::InitDone),
245 ]),
246 )
247 .map(|_| ())
248 .collect::<()>()
249 .await;
250 assert_eq!(store.get(&ObjectRef::from_obj(&cm_a)), None);
251 assert_eq!(store.get(&ObjectRef::from_obj(&cm_b)).as_deref(), Some(&cm_b));
252 }
253
254 #[tokio::test]
255 async fn reflector_store_should_not_contain_duplicates() {
256 let mut rng = rand::rng();
257 let item_dist = Uniform::new(0_u8, 100).unwrap();
258 let deleted_dist = Bernoulli::new(0.40).unwrap();
259 let store_w = store::Writer::default();
260 let store = store_w.as_reader();
261 reflector(
262 store_w,
263 stream::iter((0_u32..100_000).map(|num| {
264 let item = rng.sample(item_dist);
265 let deleted = rng.sample(deleted_dist);
266 let obj = ConfigMap {
267 metadata: ObjectMeta {
268 name: Some(item.to_string()),
269 resource_version: Some(num.to_string()),
270 ..ObjectMeta::default()
271 },
272 ..ConfigMap::default()
273 };
274 Ok(if deleted {
275 watcher::Event::Delete(obj)
276 } else {
277 watcher::Event::Apply(obj)
278 })
279 })),
280 )
281 .map_ok(|_| ())
282 .try_collect::<()>()
283 .await
284 .unwrap();
285
286 let mut seen_objects = HashMap::new();
287 for obj in store.state() {
288 assert_eq!(seen_objects.get(obj.metadata.name.as_ref().unwrap()), None);
289 seen_objects.insert(obj.metadata.name.clone().unwrap(), obj);
290 }
291 }
292}