-
-
Notifications
You must be signed in to change notification settings - Fork 320
/
mod.rs
1346 lines (1287 loc) · 55.4 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Runs a user-supplied reconciler function on objects when they (or related objects) are updated
use self::runner::Runner;
use crate::{
reflector::{
self, reflector,
store::{Store, Writer},
ObjectRef,
},
scheduler::{scheduler, ScheduleRequest},
utils::{trystream_try_via, CancelableJoinHandle, KubeRuntimeStreamExt, StreamBackoff, WatchStreamExt},
watcher::{self, metadata_watcher, watcher, Config, DefaultBackoff},
};
use backoff::backoff::Backoff;
use derivative::Derivative;
use futures::{
channel,
future::{self, BoxFuture},
ready, stream, Future, FutureExt, Stream, StreamExt, TryFuture, TryFutureExt, TryStream, TryStreamExt,
};
use kube_client::api::{Api, DynamicObject, Resource};
use pin_project::pin_project;
use serde::de::DeserializeOwned;
use std::{
fmt::{Debug, Display},
hash::Hash,
sync::Arc,
task::Poll,
time::Duration,
};
use stream::BoxStream;
use thiserror::Error;
use tokio::{runtime::Handle, time::Instant};
use tracing::{info_span, Instrument};
mod future_hash_map;
mod runner;
pub type RunnerError = runner::Error<reflector::store::WriterDropped>;
#[derive(Debug, Error)]
pub enum Error<ReconcilerErr: 'static, QueueErr: 'static> {
#[error("tried to reconcile object {0} that was not found in local store")]
ObjectNotFound(ObjectRef<DynamicObject>),
#[error("reconciler for object {1} failed")]
ReconcilerFailed(#[source] ReconcilerErr, ObjectRef<DynamicObject>),
#[error("event queue error")]
QueueError(#[source] QueueErr),
#[error("runner error")]
RunnerError(#[source] RunnerError),
}
/// Results of the reconciliation attempt
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Action {
/// Whether (and when) to next trigger the reconciliation if no external watch triggers hit
///
/// For example, use this to query external systems for updates, expire time-limited resources, or
/// (in your `error_policy`) retry after errors.
requeue_after: Option<Duration>,
}
impl Action {
/// Action to the reconciliation at this time even if no external watch triggers hit
///
/// This is the best-practice action that ensures eventual consistency of your controller
/// even in the case of missed changes (which can happen).
///
/// Watch events are not normally missed, so running this once per hour (`Default`) as a fallback is reasonable.
#[must_use]
pub fn requeue(duration: Duration) -> Self {
Self {
requeue_after: Some(duration),
}
}
/// Do nothing until a change is detected
///
/// This stops the controller periodically reconciling this object until a relevant watch event
/// was **detected**.
///
/// **Warning**: If you have watch desyncs, it is possible to miss changes entirely.
/// It is therefore not recommended to disable requeuing this way, unless you have
/// frequent changes to the underlying object, or some other hook to retain eventual consistency.
#[must_use]
pub fn await_change() -> Self {
Self { requeue_after: None }
}
}
/// Helper for building custom trigger filters, see the implementations of [`trigger_self`] and [`trigger_owners`] for some examples.
pub fn trigger_with<T, K, I, S>(
stream: S,
mapper: impl Fn(T) -> I,
) -> impl Stream<Item = Result<ReconcileRequest<K>, S::Error>>
where
S: TryStream<Ok = T>,
I: IntoIterator,
I::Item: Into<ReconcileRequest<K>>,
K: Resource,
{
stream
.map_ok(move |obj| stream::iter(mapper(obj).into_iter().map(Into::into).map(Ok)))
.try_flatten()
}
/// Enqueues the object itself for reconciliation
pub fn trigger_self<K, S>(
stream: S,
dyntype: K::DynamicType,
) -> impl Stream<Item = Result<ReconcileRequest<K>, S::Error>>
where
S: TryStream<Ok = K>,
K: Resource,
K::DynamicType: Clone,
{
trigger_with(stream, move |obj| {
Some(ReconcileRequest {
obj_ref: ObjectRef::from_obj_with(&obj, dyntype.clone()),
reason: ReconcileReason::ObjectUpdated,
})
})
}
/// Enqueues any mapper returned `K` types for reconciliation
fn trigger_others<S, K, I>(
stream: S,
mapper: impl Fn(S::Ok) -> I + Sync + Send + 'static,
dyntype: <S::Ok as Resource>::DynamicType,
) -> impl Stream<Item = Result<ReconcileRequest<K>, S::Error>>
where
// Input stream has items as some Resource (via Controller::watches)
S: TryStream,
S::Ok: Resource,
<S::Ok as Resource>::DynamicType: Clone,
// Output stream is requests for the root type K
K: Resource,
K::DynamicType: Clone,
// but the mapper can produce many of them
I: 'static + IntoIterator<Item = ObjectRef<K>>,
I::IntoIter: Send,
{
trigger_with(stream, move |obj| {
let watch_ref = ObjectRef::from_obj_with(&obj, dyntype.clone()).erase();
mapper(obj)
.into_iter()
.map(move |mapped_obj_ref| ReconcileRequest {
obj_ref: mapped_obj_ref,
reason: ReconcileReason::RelatedObjectUpdated {
obj_ref: Box::new(watch_ref.clone()),
},
})
})
}
/// Enqueues any owners of type `KOwner` for reconciliation
pub fn trigger_owners<KOwner, S>(
stream: S,
owner_type: KOwner::DynamicType,
child_type: <S::Ok as Resource>::DynamicType,
) -> impl Stream<Item = Result<ReconcileRequest<KOwner>, S::Error>>
where
S: TryStream,
S::Ok: Resource,
<S::Ok as Resource>::DynamicType: Clone,
KOwner: Resource,
KOwner::DynamicType: Clone,
{
let mapper = move |obj: S::Ok| {
let meta = obj.meta().clone();
let ns = meta.namespace;
let owner_type = owner_type.clone();
meta.owner_references
.into_iter()
.flatten()
.filter_map(move |owner| ObjectRef::from_owner_ref(ns.as_deref(), &owner, owner_type.clone()))
};
trigger_others(stream, mapper, child_type)
}
/// A request to reconcile an object, annotated with why that request was made.
///
/// NOTE: The reason is ignored for comparison purposes. This means that, for example,
/// an object can only occupy one scheduler slot, even if it has been scheduled for multiple reasons.
/// In this case, only *the first* reason is stored.
#[derive(Derivative)]
#[derivative(
Debug(bound = "K::DynamicType: Debug"),
Clone(bound = "K::DynamicType: Clone"),
PartialEq(bound = "K::DynamicType: PartialEq"),
Eq(bound = "K::DynamicType: Eq"),
Hash(bound = "K::DynamicType: Hash")
)]
pub struct ReconcileRequest<K: Resource> {
pub obj_ref: ObjectRef<K>,
#[derivative(PartialEq = "ignore", Hash = "ignore")]
pub reason: ReconcileReason,
}
impl<K: Resource> From<ObjectRef<K>> for ReconcileRequest<K> {
fn from(obj_ref: ObjectRef<K>) -> Self {
ReconcileRequest {
obj_ref,
reason: ReconcileReason::Unknown,
}
}
}
#[derive(Debug, Clone)]
pub enum ReconcileReason {
Unknown,
ObjectUpdated,
RelatedObjectUpdated { obj_ref: Box<ObjectRef<DynamicObject>> },
ReconcilerRequestedRetry,
ErrorPolicyRequestedRetry,
BulkReconcile,
Custom { reason: String },
}
impl Display for ReconcileReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ReconcileReason::Unknown => f.write_str("unknown"),
ReconcileReason::ObjectUpdated => f.write_str("object updated"),
ReconcileReason::RelatedObjectUpdated { obj_ref: object } => {
f.write_fmt(format_args!("related object updated: {object}"))
}
ReconcileReason::BulkReconcile => f.write_str("bulk reconcile requested"),
ReconcileReason::ReconcilerRequestedRetry => f.write_str("reconciler requested retry"),
ReconcileReason::ErrorPolicyRequestedRetry => f.write_str("error policy requested retry"),
ReconcileReason::Custom { reason } => f.write_str(reason),
}
}
}
const APPLIER_REQUEUE_BUF_SIZE: usize = 100;
/// Apply a reconciler to an input stream, with a given retry policy
///
/// Takes a `store` parameter for the core objects, which should usually be updated by a [`reflector()`].
///
/// The `queue` indicates which objects should be reconciled. For the core objects this will usually be
/// the [`reflector()`] (piped through [`trigger_self`]). If your core objects own any subobjects then you
/// can also make them trigger reconciliations by [merging](`futures::stream::select`) the [`reflector()`]
/// with a [`watcher()`] or [`reflector()`] for the subobject.
///
/// This is the "hard-mode" version of [`Controller`], which allows you some more customization
/// (such as triggering from arbitrary [`Stream`]s), at the cost of being a bit more verbose.
pub fn applier<K, QueueStream, ReconcilerFut, Ctx>(
mut reconciler: impl FnMut(Arc<K>, Arc<Ctx>) -> ReconcilerFut,
error_policy: impl Fn(Arc<K>, &ReconcilerFut::Error, Arc<Ctx>) -> Action,
context: Arc<Ctx>,
store: Store<K>,
queue: QueueStream,
) -> impl Stream<Item = Result<(ObjectRef<K>, Action), Error<ReconcilerFut::Error, QueueStream::Error>>>
where
K: Clone + Resource + 'static,
K::DynamicType: Debug + Eq + Hash + Clone + Unpin,
ReconcilerFut: TryFuture<Ok = Action> + Unpin,
ReconcilerFut::Error: std::error::Error + 'static,
QueueStream: TryStream,
QueueStream::Ok: Into<ReconcileRequest<K>>,
QueueStream::Error: std::error::Error + 'static,
{
let (scheduler_shutdown_tx, scheduler_shutdown_rx) = channel::oneshot::channel();
let (scheduler_tx, scheduler_rx) =
channel::mpsc::channel::<ScheduleRequest<ReconcileRequest<K>>>(APPLIER_REQUEUE_BUF_SIZE);
let error_policy = Arc::new(error_policy);
let delay_store = store.clone();
// Create a stream of ObjectRefs that need to be reconciled
trystream_try_via(
// input: stream combining scheduled tasks and user specified inputs event
Box::pin(stream::select(
// 1. inputs from users queue stream
queue
.map_err(Error::QueueError)
.map_ok(|request| ScheduleRequest {
message: request.into(),
run_at: Instant::now() + Duration::from_millis(1),
})
.on_complete(async move {
// On error: scheduler has already been shut down and there is nothing for us to do
let _ = scheduler_shutdown_tx.send(());
tracing::debug!("applier queue terminated, starting graceful shutdown")
}),
// 2. requests sent to scheduler_tx
scheduler_rx
.map(Ok)
.take_until(scheduler_shutdown_rx)
.on_complete(async { tracing::debug!("applier scheduler consumer terminated") }),
)),
// all the Oks from the select gets passed through the scheduler stream, and are then executed
move |s| {
Runner::new(scheduler(s), move |request| {
let request = request.clone();
match store.get(&request.obj_ref) {
Some(obj) => {
let scheduler_tx = scheduler_tx.clone();
let error_policy_ctx = context.clone();
let error_policy = error_policy.clone();
let reconciler_span = info_span!(
"reconciling object",
"object.ref" = %request.obj_ref,
object.reason = %request.reason
);
reconciler_span
.in_scope(|| reconciler(Arc::clone(&obj), context.clone()))
.into_future()
.then(move |res| {
let error_policy = error_policy;
RescheduleReconciliation::new(
res,
|err| error_policy(obj, err, error_policy_ctx),
request.obj_ref.clone(),
scheduler_tx,
)
// Reconciler errors are OK from the applier's PoV, we need to apply the error policy
// to them separately
.map(|res| Ok((request.obj_ref, res)))
})
.instrument(reconciler_span)
.left_future()
}
None => future::err(Error::ObjectNotFound(request.obj_ref.erase())).right_future(),
}
})
.delay_tasks_until(async move {
tracing::debug!("applier runner held until store is ready");
let res = delay_store.wait_until_ready().await;
tracing::debug!("store is ready, starting runner");
res
})
.map(|runner_res| runner_res.unwrap_or_else(|err| Err(Error::RunnerError(err))))
.on_complete(async { tracing::debug!("applier runner terminated") })
},
)
.on_complete(async { tracing::debug!("applier runner-merge terminated") })
// finally, for each completed reconcile call:
.and_then(move |(obj_ref, reconciler_result)| async move {
match reconciler_result {
Ok(action) => Ok((obj_ref, action)),
Err(err) => Err(Error::ReconcilerFailed(err, obj_ref.erase())),
}
})
.on_complete(async { tracing::debug!("applier terminated") })
}
/// Internal helper [`Future`] that reschedules reconciliation of objects (if required), in the scheduled context of the reconciler
///
/// This could be an `async fn`, but isn't because we want it to be [`Unpin`]
#[pin_project]
#[must_use]
struct RescheduleReconciliation<K: Resource, ReconcilerErr> {
reschedule_tx: channel::mpsc::Sender<ScheduleRequest<ReconcileRequest<K>>>,
reschedule_request: Option<ScheduleRequest<ReconcileRequest<K>>>,
result: Option<Result<Action, ReconcilerErr>>,
}
impl<K, ReconcilerErr> RescheduleReconciliation<K, ReconcilerErr>
where
K: Resource,
{
fn new(
result: Result<Action, ReconcilerErr>,
error_policy: impl FnOnce(&ReconcilerErr) -> Action,
obj_ref: ObjectRef<K>,
reschedule_tx: channel::mpsc::Sender<ScheduleRequest<ReconcileRequest<K>>>,
) -> Self {
let reconciler_finished_at = Instant::now();
let (action, reschedule_reason) = result.as_ref().map_or_else(
|err| (error_policy(err), ReconcileReason::ErrorPolicyRequestedRetry),
|action| (action.clone(), ReconcileReason::ReconcilerRequestedRetry),
);
Self {
reschedule_tx,
reschedule_request: action.requeue_after.map(|requeue_after| ScheduleRequest {
message: ReconcileRequest {
obj_ref,
reason: reschedule_reason,
},
run_at: reconciler_finished_at + requeue_after,
}),
result: Some(result),
}
}
}
impl<K, ReconcilerErr> Future for RescheduleReconciliation<K, ReconcilerErr>
where
K: Resource,
{
type Output = Result<Action, ReconcilerErr>;
fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
if this.reschedule_request.is_some() {
let rescheduler_ready = ready!(this.reschedule_tx.poll_ready(cx));
let reschedule_request = this
.reschedule_request
.take()
.expect("PostReconciler::reschedule_request was taken during processing");
// Failure to schedule item = in graceful shutdown mode, ignore
if let Ok(()) = rescheduler_ready {
let _ = this.reschedule_tx.start_send(reschedule_request);
}
}
Poll::Ready(
this.result
.take()
.expect("PostReconciler::result was already taken"),
)
}
}
/// Controller for a Resource `K`
///
/// A controller is an infinite stream of objects to be reconciled.
///
/// Once `run` and continuously awaited, it continuously calls out to user provided
/// `reconcile` and `error_policy` callbacks whenever relevant changes are detected
/// or if errors are seen from `reconcile`.
///
/// Reconciles are generally requested for all changes on your root objects.
/// Changes to managed child resources will also trigger the reconciler for the
/// managing object by travirsing owner references (for `Controller::owns`),
/// or traverse a custom mapping (for `Controller::watches`).
///
/// This mapping mechanism ultimately hides the reason for the reconciliation request,
/// and forces you to write an idempotent reconciler.
///
/// General setup:
/// ```no_run
/// use kube::{Api, Client, CustomResource};
/// use kube::runtime::{controller::{Controller, Action}, watcher};
/// # use serde::{Deserialize, Serialize};
/// # use tokio::time::Duration;
/// use futures::StreamExt;
/// use k8s_openapi::api::core::v1::ConfigMap;
/// use schemars::JsonSchema;
/// # use std::sync::Arc;
/// use thiserror::Error;
///
/// #[derive(Debug, Error)]
/// enum Error {}
///
/// /// A custom resource
/// #[derive(CustomResource, Debug, Clone, Deserialize, Serialize, JsonSchema)]
/// #[kube(group = "nullable.se", version = "v1", kind = "ConfigMapGenerator", namespaced)]
/// struct ConfigMapGeneratorSpec {
/// content: String,
/// }
///
/// /// The reconciler that will be called when either object change
/// async fn reconcile(g: Arc<ConfigMapGenerator>, _ctx: Arc<()>) -> Result<Action, Error> {
/// // .. use api here to reconcile a child ConfigMap with ownerreferences
/// // see configmapgen_controller example for full info
/// Ok(Action::requeue(Duration::from_secs(300)))
/// }
/// /// an error handler that will be called when the reconciler fails with access to both the
/// /// object that caused the failure and the actual error
/// fn error_policy(obj: Arc<ConfigMapGenerator>, _error: &Error, _ctx: Arc<()>) -> Action {
/// Action::requeue(Duration::from_secs(60))
/// }
///
/// /// something to drive the controller
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::try_default().await?;
/// let context = Arc::new(()); // bad empty context - put client in here
/// let cmgs = Api::<ConfigMapGenerator>::all(client.clone());
/// let cms = Api::<ConfigMap>::all(client.clone());
/// Controller::new(cmgs, watcher::Config::default())
/// .owns(cms, watcher::Config::default())
/// .run(reconcile, error_policy, context)
/// .for_each(|res| async move {
/// match res {
/// Ok(o) => println!("reconciled {:?}", o),
/// Err(e) => println!("reconcile failed: {:?}", e),
/// }
/// })
/// .await; // controller does nothing unless polled
/// Ok(())
/// }
/// ```
pub struct Controller<K>
where
K: Clone + Resource + Debug + 'static,
K::DynamicType: Eq + Hash,
{
// NB: Need to Unpin for stream::select_all
trigger_selector: stream::SelectAll<BoxStream<'static, Result<ReconcileRequest<K>, watcher::Error>>>,
trigger_backoff: Box<dyn Backoff + Send>,
/// [`run`](crate::Controller::run) starts a graceful shutdown when any of these [`Future`]s complete,
/// refusing to start any new reconciliations but letting any existing ones finish.
graceful_shutdown_selector: Vec<BoxFuture<'static, ()>>,
/// [`run`](crate::Controller::run) terminates immediately when any of these [`Future`]s complete,
/// requesting that all running reconciliations be aborted.
/// However, note that they *will* keep running until their next yield point (`.await`),
/// blocking [`tokio::runtime::Runtime`] destruction (unless you follow up by calling [`std::process::exit`] after `run`).
forceful_shutdown_selector: Vec<BoxFuture<'static, ()>>,
dyntype: K::DynamicType,
reader: Store<K>,
}
impl<K> Controller<K>
where
K: Clone + Resource + DeserializeOwned + Debug + Send + Sync + 'static,
K::DynamicType: Eq + Hash + Clone,
{
/// Create a Controller for a resource `K`
///
/// Takes an [`Api`] object that determines how the `Controller` listens for changes to the `K`.
///
/// The [`Config`] controls to the possible subset of objects of `K` that you want to manage
/// and receive reconcile events for.
/// For the full set of objects `K` in the given `Api` scope, you can use [`Config::default`].
#[must_use]
pub fn new(main_api: Api<K>, wc: Config) -> Self
where
K::DynamicType: Default,
{
Self::new_with(main_api, wc, Default::default())
}
/// Create a Controller for a resource `K`
///
/// Takes an [`Api`] object that determines how the `Controller` listens for changes to the `K`.
///
/// The [`Config`] lets you define a possible subset of objects of `K` that you want the [`Api`]
/// to watch - in the Api's configured scope - and receive reconcile events for.
/// For the full set of objects `K` in the given `Api` scope, you can use [`Config::default`].
///
/// This variant constructor is for [`dynamic`] types found through discovery. Prefer [`Controller::new`] for static types.
///
/// [`Config`]: crate::watcher::Config
/// [`Api`]: kube_client::Api
/// [`dynamic`]: kube_client::core::dynamic
/// [`Config::default`]: crate::watcher::Config::default
pub fn new_with(main_api: Api<K>, wc: Config, dyntype: K::DynamicType) -> Self {
let writer = Writer::<K>::new(dyntype.clone());
let reader = writer.as_reader();
let mut trigger_selector = stream::SelectAll::new();
let self_watcher = trigger_self(
reflector(writer, watcher(main_api, wc)).applied_objects(),
dyntype.clone(),
)
.boxed();
trigger_selector.push(self_watcher);
Self {
trigger_selector,
trigger_backoff: Box::<DefaultBackoff>::default(),
graceful_shutdown_selector: vec![
// Fallback future, ensuring that we never terminate if no additional futures are added to the selector
future::pending().boxed(),
],
forceful_shutdown_selector: vec![
// Fallback future, ensuring that we never terminate if no additional futures are added to the selector
future::pending().boxed(),
],
dyntype,
reader,
}
}
/// Create a Controller for a resource `K` from a stream of `K` objects
///
/// Same as [`Controller::new`], but instead of an `Api`, a stream of resources is used.
/// This allows for customized and pre-filtered watch streams to be used as a trigger,
/// as well as sharing input streams between multiple controllers.
///
/// **NB**: This is constructor requires an [`unstable`](https://github.com/kube-rs/kube/blob/main/kube-runtime/Cargo.toml#L17-L21) feature.
///
/// # Example:
///
/// ```no_run
/// # use futures::StreamExt;
/// # use k8s_openapi::api::apps::v1::Deployment;
/// # use kube::runtime::controller::{Action, Controller};
/// # use kube::runtime::{predicates, watcher, reflector, WatchStreamExt};
/// # use kube::{Api, Client, Error, ResourceExt};
/// # use std::sync::Arc;
/// # async fn reconcile(_: Arc<Deployment>, _: Arc<()>) -> Result<Action, Error> { Ok(Action::await_change()) }
/// # fn error_policy(_: Arc<Deployment>, _: &kube::Error, _: Arc<()>) -> Action { Action::await_change() }
/// # async fn doc(client: kube::Client) {
/// let api: Api<Deployment> = Api::default_namespaced(client);
/// let (reader, writer) = reflector::store();
/// let deploys = watcher(api, watcher::Config::default())
/// .default_backoff()
/// .reflect(writer)
/// .applied_objects()
/// .predicate_filter(predicates::generation);
///
/// Controller::for_stream(deploys, reader)
/// .run(reconcile, error_policy, Arc::new(()))
/// .for_each(|_| std::future::ready(()))
/// .await;
/// # }
/// ```
///
/// Prefer [`Controller::new`] if you do not need to share the stream, or do not need pre-filtering.
#[cfg(feature = "unstable-runtime-stream-control")]
pub fn for_stream(
trigger: impl Stream<Item = Result<K, watcher::Error>> + Send + 'static,
reader: Store<K>,
) -> Self
where
K::DynamicType: Default,
{
Self::for_stream_with(trigger, reader, Default::default())
}
/// Create a Controller for a resource `K` from a stream of `K` objects
///
/// Same as [`Controller::new`], but instead of an `Api`, a stream of resources is used.
/// This allows for customized and pre-filtered watch streams to be used as a trigger,
/// as well as sharing input streams between multiple controllers.
///
/// **NB**: This is constructor requires an [`unstable`](https://github.com/kube-rs/kube/blob/main/kube-runtime/Cargo.toml#L17-L21) feature.
///
/// Prefer [`Controller::new`] if you do not need to share the stream, or do not need pre-filtering.
///
/// This variant constructor is for [`dynamic`] types found through discovery. Prefer [`Controller::for_stream`] for static types.
///
/// [`dynamic`]: kube_client::core::dynamic
#[cfg(feature = "unstable-runtime-stream-control")]
pub fn for_stream_with(
trigger: impl Stream<Item = Result<K, watcher::Error>> + Send + 'static,
reader: Store<K>,
dyntype: K::DynamicType,
) -> Self {
let mut trigger_selector = stream::SelectAll::new();
let self_watcher = trigger_self(trigger, dyntype.clone()).boxed();
trigger_selector.push(self_watcher);
Self {
trigger_selector,
trigger_backoff: Box::<DefaultBackoff>::default(),
graceful_shutdown_selector: vec![
// Fallback future, ensuring that we never terminate if no additional futures are added to the selector
future::pending().boxed(),
],
forceful_shutdown_selector: vec![
// Fallback future, ensuring that we never terminate if no additional futures are added to the selector
future::pending().boxed(),
],
dyntype,
reader,
}
}
/// Specify the backoff policy for "trigger" watches
///
/// This includes the core watch, as well as auxilary watches introduced by [`Self::owns`] and [`Self::watches`].
///
/// The [`default_backoff`](crate::watcher::default_backoff) follows client-go conventions,
/// but can be overridden by calling this method.
#[must_use]
pub fn trigger_backoff(mut self, backoff: impl Backoff + Send + 'static) -> Self {
self.trigger_backoff = Box::new(backoff);
self
}
/// Retrieve a copy of the reader before starting the controller
pub fn store(&self) -> Store<K> {
self.reader.clone()
}
/// Specify `Child` objects which `K` owns and should be watched
///
/// Takes an [`Api`] object that determines how the `Controller` listens for changes to the `Child`.
/// All owned `Child` objects **must** contain an [`OwnerReference`] pointing back to a `K`.
///
/// The [`watcher::Config`] controls the subset of `Child` objects that you want the [`Api`]
/// to watch - in the Api's configured scope - and receive reconcile events for.
/// To watch the full set of `Child` objects in the given `Api` scope, you can use [`watcher::Config::default`].
///
/// [`OwnerReference`]: k8s_openapi::apimachinery::pkg::apis::meta::v1::OwnerReference
#[must_use]
pub fn owns<Child: Clone + Resource<DynamicType = ()> + DeserializeOwned + Debug + Send + 'static>(
self,
api: Api<Child>,
wc: Config,
) -> Self {
self.owns_with(api, (), wc)
}
/// Specify `Child` objects which `K` owns and should be watched
///
/// Same as [`Controller::owns`], but accepts a `DynamicType` so it can be used with dynamic resources.
#[must_use]
pub fn owns_with<Child: Clone + Resource + DeserializeOwned + Debug + Send + 'static>(
mut self,
api: Api<Child>,
dyntype: Child::DynamicType,
wc: Config,
) -> Self
where
Child::DynamicType: Debug + Eq + Hash + Clone,
{
// TODO: call owns_stream_with when it's stable
let child_watcher = trigger_owners(
metadata_watcher(api, wc).touched_objects(),
self.dyntype.clone(),
dyntype,
);
self.trigger_selector.push(child_watcher.boxed());
self
}
/// Trigger the reconciliation process for a stream of `Child` objects of the owner `K`
///
/// Same as [`Controller::owns`], but instead of an `Api`, a stream of resources is used.
/// This allows for customized and pre-filtered watch streams to be used as a trigger,
/// as well as sharing input streams between multiple controllers.
///
/// **NB**: This is constructor requires an [`unstable`](https://github.com/kube-rs/kube/blob/main/kube-runtime/Cargo.toml#L17-L21) feature.
///
/// Watcher streams passed in here should be filtered first through `touched_objects`.
///
/// # Example:
///
/// ```no_run
/// # use futures::StreamExt;
/// # use k8s_openapi::api::core::v1::ConfigMap;
/// # use k8s_openapi::api::apps::v1::StatefulSet;
/// # use kube::runtime::controller::Action;
/// # use kube::runtime::{predicates, metadata_watcher, watcher, Controller, WatchStreamExt};
/// # use kube::{Api, Client, Error, ResourceExt};
/// # use std::sync::Arc;
/// # type CustomResource = ConfigMap;
/// # async fn reconcile(_: Arc<CustomResource>, _: Arc<()>) -> Result<Action, Error> { Ok(Action::await_change()) }
/// # fn error_policy(_: Arc<CustomResource>, _: &kube::Error, _: Arc<()>) -> Action { Action::await_change() }
/// # async fn doc(client: kube::Client) {
/// let sts_stream = metadata_watcher(Api::<StatefulSet>::all(client.clone()), watcher::Config::default())
/// .touched_objects()
/// .predicate_filter(predicates::generation);
///
/// Controller::new(Api::<CustomResource>::all(client), watcher::Config::default())
/// .owns_stream(sts_stream)
/// .run(reconcile, error_policy, Arc::new(()))
/// .for_each(|_| std::future::ready(()))
/// .await;
/// # }
/// ```
#[cfg(feature = "unstable-runtime-stream-control")]
#[must_use]
pub fn owns_stream<Child: Resource<DynamicType = ()> + Send + 'static>(
self,
trigger: impl Stream<Item = Result<Child, watcher::Error>> + Send + 'static,
) -> Self {
self.owns_stream_with(trigger, ())
}
/// Trigger the reconciliation process for a stream of `Child` objects of the owner `K`
///
/// Same as [`Controller::owns`], but instead of an `Api`, a stream of resources is used.
/// This allows for customized and pre-filtered watch streams to be used as a trigger,
/// as well as sharing input streams between multiple controllers.
///
/// **NB**: This is constructor requires an [`unstable`](https://github.com/kube-rs/kube/blob/main/kube-runtime/Cargo.toml#L17-L21) feature.
///
/// Same as [`Controller::owns_stream`], but accepts a `DynamicType` so it can be used with dynamic resources.
#[cfg(feature = "unstable-runtime-stream-control")]
#[must_use]
pub fn owns_stream_with<Child: Resource + Send + 'static>(
mut self,
trigger: impl Stream<Item = Result<Child, watcher::Error>> + Send + 'static,
dyntype: Child::DynamicType,
) -> Self
where
Child::DynamicType: Debug + Eq + Hash + Clone,
{
let child_watcher = trigger_owners(trigger, self.dyntype.clone(), dyntype);
self.trigger_selector.push(child_watcher.boxed());
self
}
/// Specify `Watched` object which `K` has a custom relation to and should be watched
///
/// To define the `Watched` relation with `K`, you **must** define a custom relation mapper, which,
/// when given a `Watched` object, returns an option or iterator of relevant `ObjectRef<K>` to reconcile.
///
/// If the relation `K` has to `Watched` is that `K` owns `Watched`, consider using [`Controller::owns`].
///
/// Takes an [`Api`] object that determines how the `Controller` listens for changes to the `Watched`.
///
/// The [`watcher::Config`] controls the subset of `Watched` objects that you want the [`Api`]
/// to watch - in the Api's configured scope - and run through the custom mapper.
/// To watch the full set of `Watched` objects in given the `Api` scope, you can use [`watcher::Config::default`].
///
/// # Example
///
/// Tracking cross cluster references using the [Operator-SDK] annotations.
///
/// ```
/// # use kube::runtime::{Controller, controller::Action, reflector::ObjectRef, watcher};
/// # use kube::{Api, ResourceExt};
/// # use k8s_openapi::api::core::v1::{ConfigMap, Namespace};
/// # use futures::StreamExt;
/// # use std::sync::Arc;
/// # type WatchedResource = Namespace;
/// # struct Context;
/// # async fn reconcile(_: Arc<ConfigMap>, _: Arc<Context>) -> Result<Action, kube::Error> {
/// # Ok(Action::await_change())
/// # };
/// # fn error_policy(_: Arc<ConfigMap>, _: &kube::Error, _: Arc<Context>) -> Action {
/// # Action::await_change()
/// # }
/// # async fn doc(client: kube::Client) -> Result<(), Box<dyn std::error::Error>> {
/// # let memcached = Api::<ConfigMap>::all(client.clone());
/// # let context = Arc::new(Context);
/// Controller::new(memcached, watcher::Config::default())
/// .watches(
/// Api::<WatchedResource>::all(client.clone()),
/// watcher::Config::default(),
/// |ar| {
/// let prt = ar
/// .annotations()
/// .get("operator-sdk/primary-resource-type")
/// .map(String::as_str);
///
/// if prt != Some("Memcached.cache.example.com") {
/// return None;
/// }
///
/// let (namespace, name) = ar
/// .annotations()
/// .get("operator-sdk/primary-resource")?
/// .split_once('/')?;
///
/// Some(ObjectRef::new(name).within(namespace))
/// }
/// )
/// .run(reconcile, error_policy, context)
/// .for_each(|_| futures::future::ready(()))
/// .await;
/// # Ok(())
/// # }
/// ```
///
/// [Operator-SDK]: https://sdk.operatorframework.io/docs/building-operators/ansible/reference/retroactively-owned-resources/
#[must_use]
pub fn watches<Other, I>(
self,
api: Api<Other>,
wc: Config,
mapper: impl Fn(Other) -> I + Sync + Send + 'static,
) -> Self
where
Other: Clone + Resource + DeserializeOwned + Debug + Send + 'static,
Other::DynamicType: Default + Debug + Clone + Eq + Hash,
I: 'static + IntoIterator<Item = ObjectRef<K>>,
I::IntoIter: Send,
{
self.watches_with(api, Default::default(), wc, mapper)
}
/// Specify `Watched` object which `K` has a custom relation to and should be watched
///
/// Same as [`Controller::watches`], but accepts a `DynamicType` so it can be used with dynamic resources.
#[must_use]
pub fn watches_with<Other, I>(
mut self,
api: Api<Other>,
dyntype: Other::DynamicType,
wc: Config,
mapper: impl Fn(Other) -> I + Sync + Send + 'static,
) -> Self
where
Other: Clone + Resource + DeserializeOwned + Debug + Send + 'static,
I: 'static + IntoIterator<Item = ObjectRef<K>>,
I::IntoIter: Send,
Other::DynamicType: Debug + Clone + Eq + Hash,
{
let other_watcher = trigger_others(watcher(api, wc).touched_objects(), mapper, dyntype);
self.trigger_selector.push(other_watcher.boxed());
self
}
/// Trigger the reconciliation process for a stream of `Other` objects related to a `K`
///
/// Same as [`Controller::watches`], but instead of an `Api`, a stream of resources is used.
/// This allows for customized and pre-filtered watch streams to be used as a trigger,
/// as well as sharing input streams between multiple controllers.
///
/// **NB**: This is constructor requires an [`unstable`](https://github.com/kube-rs/kube/blob/main/kube-runtime/Cargo.toml#L17-L21) feature.
///
/// Watcher streams passed in here should be filtered first through `touched_objects`.
///
/// # Example:
///
/// ```no_run
/// # use futures::StreamExt;
/// # use k8s_openapi::api::core::v1::ConfigMap;
/// # use k8s_openapi::api::apps::v1::DaemonSet;
/// # use kube::runtime::controller::Action;
/// # use kube::runtime::{predicates, reflector::ObjectRef, watcher, Controller, WatchStreamExt};
/// # use kube::{Api, Client, Error, ResourceExt};
/// # use std::sync::Arc;
/// # type CustomResource = ConfigMap;
/// # async fn reconcile(_: Arc<CustomResource>, _: Arc<()>) -> Result<Action, Error> { Ok(Action::await_change()) }
/// # fn error_policy(_: Arc<CustomResource>, _: &kube::Error, _: Arc<()>) -> Action { Action::await_change() }
/// fn mapper(_: DaemonSet) -> Option<ObjectRef<CustomResource>> { todo!() }
/// # async fn doc(client: kube::Client) {
/// let api: Api<DaemonSet> = Api::all(client.clone());
/// let cr: Api<CustomResource> = Api::all(client.clone());
/// let daemons = watcher(api, watcher::Config::default())
/// .touched_objects()
/// .predicate_filter(predicates::generation);
///
/// Controller::new(cr, watcher::Config::default())
/// .watches_stream(daemons, mapper)
/// .run(reconcile, error_policy, Arc::new(()))
/// .for_each(|_| std::future::ready(()))
/// .await;
/// # }
/// ```
#[cfg(feature = "unstable-runtime-stream-control")]
#[must_use]
pub fn watches_stream<Other, I>(
self,
trigger: impl Stream<Item = Result<Other, watcher::Error>> + Send + 'static,
mapper: impl Fn(Other) -> I + Sync + Send + 'static,
) -> Self
where
Other: Clone + Resource + DeserializeOwned + Debug + Send + 'static,
Other::DynamicType: Default + Debug + Clone,
I: 'static + IntoIterator<Item = ObjectRef<K>>,
I::IntoIter: Send,
{
self.watches_stream_with(trigger, mapper, Default::default())
}
/// Trigger the reconciliation process for a stream of `Other` objects related to a `K`
///
/// Same as [`Controller::owns`], but instead of an `Api`, a stream of resources is used.
/// This allows for customized and pre-filtered watch streams to be used as a trigger,
/// as well as sharing input streams between multiple controllers.
///
/// **NB**: This is constructor requires an [`unstable`](https://github.com/kube-rs/kube/blob/main/kube-runtime/Cargo.toml#L17-L21) feature.
///
/// Same as [`Controller::watches_stream`], but accepts a `DynamicType` so it can be used with dynamic resources.
#[cfg(feature = "unstable-runtime-stream-control")]
#[must_use]
pub fn watches_stream_with<Other, I>(
mut self,
trigger: impl Stream<Item = Result<Other, watcher::Error>> + Send + 'static,
mapper: impl Fn(Other) -> I + Sync + Send + 'static,
dyntype: Other::DynamicType,
) -> Self
where
Other: Clone + Resource + DeserializeOwned + Debug + Send + 'static,
Other::DynamicType: Debug + Clone,
I: 'static + IntoIterator<Item = ObjectRef<K>>,
I::IntoIter: Send,
{
let other_watcher = trigger_others(trigger, mapper, dyntype);
self.trigger_selector.push(other_watcher.boxed());
self
}
/// Trigger a reconciliation for all managed objects whenever `trigger` emits a value
///
/// For example, this can be used to reconcile all objects whenever the controller's configuration changes.
///
/// To reconcile all objects when a new line is entered:
///
/// ```
/// # async {
/// use futures::stream::StreamExt;
/// use k8s_openapi::api::core::v1::ConfigMap;
/// use kube::{
/// Client,
/// api::{Api, ResourceExt},
/// runtime::{
/// controller::{Controller, Action},
/// watcher,
/// },
/// };
/// use std::{convert::Infallible, io::BufRead, sync::Arc};
/// let (mut reload_tx, reload_rx) = futures::channel::mpsc::channel(0);
/// // Using a regular background thread since tokio::io::stdin() doesn't allow aborting reads,
/// // and its worker prevents the Tokio runtime from shutting down.
/// std::thread::spawn(move || {
/// for _ in std::io::BufReader::new(std::io::stdin()).lines() {
/// let _ = reload_tx.try_send(());
/// }
/// });
/// Controller::new(
/// Api::<ConfigMap>::all(Client::try_default().await.unwrap()),
/// watcher::Config::default(),
/// )
/// .reconcile_all_on(reload_rx.map(|_| ()))
/// .run(
/// |o, _| async move {
/// println!("Reconciling {}", o.name_any());