-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathindex.rs
More file actions
2289 lines (2062 loc) · 82.4 KB
/
index.rs
File metadata and controls
2289 lines (2062 loc) · 82.4 KB
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
//! Keeps track of `Pod`, `Server`, and `ServerAuthorization` resources to
//! provide a dynamic server configuration for all known ports on all pods.
//!
//! The `Index` type exposes a single public method: `Index::pod_server_rx`,
//! which is used to lookup pod/ports (i.e. by the gRPC API). Otherwise, it
//! implements `kubert::index::IndexNamespacedResource` for the indexed
//! kubernetes resources.
use super::{
authorization_policy, meshtls_authentication, network_authentication, ratelimit_policy,
routes::RouteBinding, server, server_authorization, workload,
};
use crate::{
ports::{PortHasher, PortMap, PortSet},
routes::{ExplicitGKN, ImpliedGKN},
ClusterInfo, DefaultPolicy,
};
use ahash::{AHashMap as HashMap, AHashSet as HashSet};
use anyhow::{anyhow, bail, Result};
use linkerd_policy_controller_core::{
inbound::{
AuthorizationRef, ClientAuthentication, ClientAuthorization, GrpcRoute, HttpRoute,
InboundRouteRule, InboundServer, Limit, Override, ProxyProtocol, RateLimit, RouteRef,
ServerRef,
},
routes::{GroupKindName, HttpRouteMatch, Method, PathMatch},
IdentityMatch, Ipv4Net, Ipv6Net, NetworkMatch,
};
use linkerd_policy_controller_k8s_api::{
self as k8s, gateway as k8s_gateway_api, policy::server::Port, policy::server::Selector,
ResourceExt,
};
use parking_lot::RwLock;
use std::{
collections::{hash_map::Entry, BTreeSet},
num::NonZeroU16,
sync::Arc,
};
use tokio::sync::watch;
use tracing::info_span;
mod grpc;
mod http;
pub mod metrics;
pub type SharedIndex = Arc<RwLock<Index>>;
/// Holds all indexing state. Owned and updated by a single task that processes
/// watch events, publishing results to the shared lookup map for quick lookups
/// in the API server.
#[derive(Debug)]
pub struct Index {
cluster_info: Arc<ClusterInfo>,
namespaces: NamespaceIndex,
authentications: AuthenticationNsIndex,
}
/// Holds all `Pod`, `Server`, and `ServerAuthorization` indices by-namespace.
#[derive(Debug)]
struct NamespaceIndex {
cluster_info: Arc<ClusterInfo>,
by_ns: HashMap<String, Namespace>,
}
/// Holds all `NetworkAuthentication` and `MeshTLSAuthentication` indices by-namespace.
///
/// This is separate from `NamespaceIndex` because authorization policies may reference
/// authentication resources across namespaces.
#[derive(Debug, Default)]
struct AuthenticationNsIndex {
by_ns: HashMap<String, AuthenticationIndex>,
}
/// Holds `Pod`, `ExternalWorkload`, `Server`, and `ServerAuthorization` indices for a single namespace.
#[derive(Debug)]
struct Namespace {
pods: PodIndex,
external_workloads: ExternalWorkloadIndex,
policy: PolicyIndex,
}
/// Holds all pod data for a single namespace.
#[derive(Debug)]
struct PodIndex {
namespace: String,
by_name: HashMap<String, Pod>,
}
/// Holds a single pod's data with the server watches for all known ports.
///
/// The set of ports/servers is updated as clients discover server configuration
/// or as `Server` resources select a port.
#[derive(Debug)]
struct Pod {
meta: workload::Meta,
/// The pod's named container ports. Used by `Server` port selectors.
///
/// A pod may have multiple ports with the same name. E.g., each container
/// may have its own `admin-http` port.
port_names: HashMap<String, PortSet>,
/// All known TCP server ports. This may be updated by
/// `Namespace::reindex`--when a port is selected by a `Server`--or by
/// `Namespace::get_pod_server` when a client discovers a port that has no
/// configured server (and i.e. uses the default policy).
port_servers: PortMap<WorkloadPortServer>,
/// The pod's probe ports and their respective paths.
///
/// In order for the policy controller to authorize probes, it must be
/// aware of the probe ports and the expected paths on which probes are
/// expected.
probes: PortMap<BTreeSet<String>>,
}
/// Holds the state of a single port on a workload (e.g. a pod or an external
/// workload).
#[derive(Debug)]
struct WorkloadPortServer {
/// The name of the server resource that matches this port. Unset when no
/// server resources match this pod/port (and, i.e., the default policy is
/// used).
name: Option<String>,
/// A sender used to broadcast workload port server updates.
watch: watch::Sender<InboundServer>,
}
/// Holds all external workload data for a single namespace
#[derive(Debug)]
struct ExternalWorkloadIndex {
namespace: String,
by_name: HashMap<String, ExternalWorkload>,
}
/// Holds data for a single external workload, with server watches for all known
/// ports.
///
/// The set of ports / servers is updated as clients discover server
/// configuration or as `Server` resources select a port.
#[derive(Debug)]
struct ExternalWorkload {
meta: workload::Meta,
// The workload's named container ports. Used by `Server` port selectors.
//
// A workload will not have multiple ports with the same name, e.g. two
// `admin-http` ports pointing to different numerical values.
port_names: HashMap<String, NonZeroU16>,
/// All known TCP server ports.
port_servers: PortMap<WorkloadPortServer>,
}
/// Holds the state of policy resources for a single namespace.
#[derive(Debug)]
struct PolicyIndex {
namespace: String,
cluster_info: Arc<ClusterInfo>,
servers: HashMap<String, server::Server>,
server_authorizations: HashMap<String, server_authorization::ServerAuthz>,
authorization_policies: HashMap<String, authorization_policy::Spec>,
ratelimit_policies: HashMap<String, ratelimit_policy::Spec>,
http_routes: HashMap<GroupKindName, RouteBinding<HttpRoute>>,
grpc_routes: HashMap<GroupKindName, RouteBinding<GrpcRoute>>,
}
#[derive(Debug, Default)]
struct AuthenticationIndex {
meshtls: HashMap<String, meshtls_authentication::Spec>,
network: HashMap<String, network_authentication::Spec>,
}
struct NsUpdate<K, T> {
added: Vec<(K, T)>,
removed: HashSet<K>,
}
// === impl Index ===
impl Index {
pub fn shared(cluster_info: impl Into<Arc<ClusterInfo>>) -> SharedIndex {
let cluster_info = cluster_info.into();
Arc::new(RwLock::new(Self {
cluster_info: cluster_info.clone(),
namespaces: NamespaceIndex {
cluster_info,
by_ns: HashMap::default(),
},
authentications: AuthenticationNsIndex::default(),
}))
}
/// Obtains a pod:port's server receiver.
///
/// An error is returned if the pod is not found. If the port is not found,
/// a default is server is created.
pub fn pod_server_rx(
&mut self,
namespace: &str,
pod: &str,
port: NonZeroU16,
) -> Result<watch::Receiver<InboundServer>> {
let ns = self
.namespaces
.by_ns
.get_mut(namespace)
.ok_or_else(|| anyhow::anyhow!("namespace not found: {}", namespace))?;
let pod = ns
.pods
.by_name
.get_mut(pod)
.ok_or_else(|| anyhow::anyhow!("pod {}.{} not found", pod, namespace))?;
Ok(pod
.port_server_or_default(port, &self.cluster_info)
.watch
.subscribe())
}
/// Obtains an external_workload:port's server receiver.
///
/// An error is returned if the external workload is not found. If the port
/// is not found, a default server is created.
pub fn external_workload_server_rx(
&mut self,
namespace: &str,
workload: &str,
port: NonZeroU16,
) -> Result<watch::Receiver<InboundServer>> {
let ns = self
.namespaces
.by_ns
.get_mut(namespace)
.ok_or_else(|| anyhow::anyhow!("namespace not found: {}", namespace))?;
let external_workload =
ns.external_workloads
.by_name
.get_mut(workload)
.ok_or_else(|| {
anyhow::anyhow!("external workload {}.{} not found", workload, namespace)
})?;
Ok(external_workload
.port_server_or_default(port, &self.cluster_info)
.watch
.subscribe())
}
fn ns_with_reindex(&mut self, namespace: String, f: impl FnOnce(&mut Namespace) -> bool) {
self.namespaces
.get_with_reindex(namespace, &self.authentications, f)
}
fn ns_or_default_with_reindex(
&mut self,
namespace: String,
f: impl FnOnce(&mut Namespace) -> bool,
) {
self.namespaces
.get_or_default_with_reindex(namespace, &self.authentications, f)
}
fn reindex_all(&mut self) {
tracing::debug!("Reindexing all namespaces");
for ns in self.namespaces.by_ns.values_mut() {
ns.reindex(&self.authentications);
}
}
fn apply_http_route<R>(&mut self, route: R)
where
R: ResourceExt<DynamicType = ()>,
RouteBinding<HttpRoute>: TryFrom<R>,
<RouteBinding<HttpRoute> as TryFrom<R>>::Error: std::fmt::Display,
{
let ns = route.namespace().expect("HttpRoute must have a namespace");
let name = route.name_unchecked();
let gkn = route.gkn();
let _span = info_span!("apply httproute", %ns, %name).entered();
let route_binding = match route.try_into() {
Ok(binding) => binding,
Err(error) => {
tracing::info!(%ns, %name, %error, "Ignoring HTTPRoute");
return;
}
};
self.ns_or_default_with_reindex(ns, |ns| ns.policy.update_http_route(gkn, route_binding))
}
fn reset_http_route<R>(&mut self, routes: Vec<R>, deleted: HashMap<String, HashSet<String>>)
where
R: ResourceExt<DynamicType = ()>,
RouteBinding<HttpRoute>: TryFrom<R>,
<RouteBinding<HttpRoute> as TryFrom<R>>::Error: std::fmt::Display,
{
let _span = info_span!("httproute reset").entered();
// Aggregate all of the updates by namespace so that we only reindex
// once per namespace.
type Ns = NsUpdate<GroupKindName, RouteBinding<HttpRoute>>;
let mut updates_by_ns = HashMap::<String, Ns>::default();
for route in routes.into_iter() {
let namespace = route.namespace().expect("HttpRoute must be namespaced");
let name = route.name_unchecked();
let gkn = route.gkn();
let route_binding = match route.try_into() {
Ok(binding) => binding,
Err(error) => {
tracing::info!(ns = %namespace, %name, %error, "Ignoring HTTPRoute");
continue;
}
};
updates_by_ns
.entry(namespace)
.or_default()
.added
.push((gkn, route_binding));
}
for (ns, names) in deleted.into_iter() {
let removed = names
.into_iter()
.map(|name| GroupKindName {
group: R::group(&()),
kind: R::kind(&()),
name: name.into(),
})
.collect();
updates_by_ns.entry(ns).or_default().removed = removed;
}
for (namespace, Ns { added, removed }) in updates_by_ns.into_iter() {
if added.is_empty() {
// If there are no live resources in the namespace, we do not
// want to create a default namespace instance, we just want to
// clear out all resources for the namespace (and then drop the
// whole namespace, if necessary).
self.ns_with_reindex(namespace, |ns| {
ns.policy.http_routes.clear();
true
});
} else {
// Otherwise, we take greater care to reindex only when the
// state actually changed. The vast majority of resets will see
// no actual data change.
self.ns_or_default_with_reindex(namespace, |ns| {
let mut changed = !removed.is_empty();
for gkn in removed.into_iter() {
ns.policy.http_routes.remove(&gkn);
}
for (gkn, route_binding) in added.into_iter() {
changed = ns.policy.update_http_route(gkn, route_binding) || changed;
}
changed
});
}
}
}
fn delete_http_route(&mut self, ns: String, gkn: GroupKindName) {
let _span = info_span!("delete httproute", %ns, route = ?gkn).entered();
self.ns_with_reindex(ns, |ns| ns.policy.http_routes.remove(&gkn).is_some())
}
fn apply_grpc_route(&mut self, route: k8s_gateway_api::GrpcRoute) {
let ns = route.namespace().expect("GrpcRoute must have a namespace");
let name = route.name_unchecked();
let gkn = route.gkn();
let _span = info_span!("apply grpcroute", %ns, %name).entered();
let route_binding = match route.try_into() {
Ok(binding) => binding,
Err(error) => {
tracing::info!(%ns, %name, %error, "Ignoring GrpcRoute");
return;
}
};
self.ns_or_default_with_reindex(ns, |ns| ns.policy.update_grpc_route(gkn, route_binding))
}
#[tracing::instrument(skip_all)]
fn reset_grpc_route(
&mut self,
routes: Vec<k8s_gateway_api::GrpcRoute>,
deleted: HashMap<String, HashSet<String>>,
) {
// Aggregate all of the updates by namespace so that we only reindex
// once per namespace.
type Ns = NsUpdate<GroupKindName, RouteBinding<GrpcRoute>>;
let mut updates_by_ns = HashMap::<String, Ns>::default();
for route in routes.into_iter() {
let namespace = route.namespace().expect("GrpcRoute must be namespaced");
let name = route.name_unchecked();
let gkn = route.gkn();
let route_binding = match route.try_into() {
Ok(binding) => binding,
Err(error) => {
tracing::info!(ns = %namespace, %name, %error, "Ignoring GrpcRoute");
continue;
}
};
updates_by_ns
.entry(namespace)
.or_default()
.added
.push((gkn, route_binding));
}
for (ns, names) in deleted.into_iter() {
let removed = names
.into_iter()
.map(|name| name.gkn::<k8s_gateway_api::GrpcRoute>())
.collect();
updates_by_ns.entry(ns).or_default().removed = removed;
}
for (namespace, Ns { added, removed }) in updates_by_ns.into_iter() {
if added.is_empty() {
// If there are no live resources in the namespace, we do not
// want to create a default namespace instance, we just want to
// clear out all resources for the namespace (and then drop the
// whole namespace, if necessary).
self.ns_with_reindex(namespace, |ns| {
ns.policy.grpc_routes.clear();
true
});
} else {
// Otherwise, we take greater care to reindex only when the
// state actually changed. The vast majority of resets will see
// no actual data change.
self.ns_or_default_with_reindex(namespace, |ns| {
let mut changed = !removed.is_empty();
for gkn in removed.into_iter() {
ns.policy.grpc_routes.remove(&gkn);
}
for (gkn, route_binding) in added.into_iter() {
changed = ns.policy.update_grpc_route(gkn, route_binding) || changed;
}
changed
});
}
}
}
fn delete_grpc_route(&mut self, ns: String, gkn: GroupKindName) {
let _span = info_span!("delete grpcroute", %ns, route = ?gkn).entered();
self.ns_with_reindex(ns, |ns| ns.policy.grpc_routes.remove(&gkn).is_some())
}
}
impl kubert::index::IndexNamespacedResource<k8s::Pod> for Index {
fn apply(&mut self, pod: k8s::Pod) {
let namespace = pod.namespace().unwrap();
let name = pod.name_unchecked();
let _span = info_span!("apply", ns = %namespace, %name).entered();
let port_names = pod
.spec
.as_ref()
.map(workload::pod_tcp_ports_by_name)
.unwrap_or_default();
let probes = pod
.spec
.as_ref()
.map(workload::pod_http_probes)
.unwrap_or_default();
let meta = workload::Meta::from_metadata(pod.metadata);
// Add or update the pod. If the pod was not already present in the
// index with the same metadata, index it against the policy resources,
// updating its watches.
let ns = self.namespaces.get_or_default(namespace);
match ns.pods.update(name, meta, port_names, probes) {
Ok(None) => {}
Ok(Some(pod)) => pod.reindex_servers(&ns.policy, &self.authentications),
Err(error) => {
tracing::error!(%error, "Illegal pod update");
}
}
}
fn delete(&mut self, ns: String, name: String) {
tracing::debug!(%ns, %name, "delete");
if let Entry::Occupied(mut ns) = self.namespaces.by_ns.entry(ns) {
// Once the pod is removed, there's nothing else to update. Any open
// watches will complete. No other parts of the index need to be
// updated.
if ns.get_mut().pods.by_name.remove(&name).is_some() && ns.get().is_empty() {
tracing::debug!(namespace = ns.key(), "Removing empty namespace index");
ns.remove();
}
}
}
// Since apply only reindexes a single pod at a time, there's no need to
// handle resets specially.
}
impl kubert::index::IndexNamespacedResource<k8s::external_workload::ExternalWorkload> for Index {
fn apply(&mut self, ext_workload: k8s::external_workload::ExternalWorkload) {
let ns = ext_workload.namespace().unwrap();
let name = ext_workload.name_unchecked();
let _span = info_span!("apply", %ns, %name).entered();
// Extract ports and settings.
// Note: external workloads do not have any probe paths to synthesise
// default policies for.
let port_names = workload::external_tcp_ports_by_name(&ext_workload.spec);
let meta = workload::Meta::from_metadata(ext_workload.metadata);
// Add or update the workload.
//
// If the resource is present in the index, but its metadata has
// changed, then it means the watches need to get an update.
let ns = self.namespaces.get_or_default(ns);
match ns.external_workloads.update(name, meta, port_names) {
// No update
Ok(None) => {}
// Update, so re-index
Ok(Some(workload)) => workload.reindex_servers(&ns.policy, &self.authentications),
Err(error) => {
tracing::error!(%error, "Illegal external workload update");
}
}
}
fn delete(&mut self, ns: String, name: String) {
tracing::debug!(%ns, %name, "delete");
if let Entry::Occupied(mut ns) = self.namespaces.by_ns.entry(ns) {
// Once the external workload is removed, there's nothing else to
// update. Any open watches will complete. No other parts of the
// index need to be updated.
if ns
.get_mut()
.external_workloads
.by_name
.remove(&name)
.is_some()
&& ns.get().is_empty()
{
ns.remove();
}
}
}
// Since apply only reindexes a single external workload at a time, there's no need to
// handle resets specially.
}
impl kubert::index::IndexNamespacedResource<k8s::policy::Server> for Index {
fn apply(&mut self, srv: k8s::policy::Server) {
let ns = srv.namespace().expect("server must be namespaced");
let name = srv.name_unchecked();
let _span = info_span!("apply", %ns, %name).entered();
let server = server::Server::from_resource(srv, &self.cluster_info);
self.ns_or_default_with_reindex(ns, |ns| ns.policy.update_server(name, server))
}
fn delete(&mut self, ns: String, name: String) {
let _span = info_span!("delete", %ns, %name).entered();
self.ns_with_reindex(ns, |ns| ns.policy.servers.remove(&name).is_some())
}
fn reset(&mut self, srvs: Vec<k8s::policy::Server>, deleted: HashMap<String, HashSet<String>>) {
let _span = info_span!("reset").entered();
// Aggregate all of the updates by namespace so that we only reindex
// once per namespace.
type Ns = NsUpdate<String, server::Server>;
let mut updates_by_ns = HashMap::<String, Ns>::default();
for srv in srvs.into_iter() {
let namespace = srv.namespace().expect("server must be namespaced");
let name = srv.name_unchecked();
let server = server::Server::from_resource(srv, &self.cluster_info);
updates_by_ns
.entry(namespace)
.or_default()
.added
.push((name, server));
}
for (ns, names) in deleted.into_iter() {
updates_by_ns.entry(ns).or_default().removed = names;
}
for (namespace, Ns { added, removed }) in updates_by_ns.into_iter() {
if added.is_empty() {
// If there are no live resources in the namespace, we do not
// want to create a default namespace instance, we just want to
// clear out all resources for the namespace (and then drop the
// whole namespace, if necessary).
self.ns_with_reindex(namespace, |ns| {
ns.policy.servers.clear();
true
});
} else {
// Otherwise, we take greater care to reindex only when the
// state actually changed. The vast majority of resets will see
// no actual data change.
self.ns_or_default_with_reindex(namespace, |ns| {
let mut changed = !removed.is_empty();
for name in removed.into_iter() {
ns.policy.servers.remove(&name);
}
for (name, server) in added.into_iter() {
changed = ns.policy.update_server(name, server) || changed;
}
changed
});
}
}
}
}
impl kubert::index::IndexNamespacedResource<k8s::policy::ServerAuthorization> for Index {
fn apply(&mut self, saz: k8s::policy::ServerAuthorization) {
let ns = saz.namespace().unwrap();
let name = saz.name_unchecked();
let _span = info_span!("apply", %ns, %name).entered();
match server_authorization::ServerAuthz::from_resource(saz, &self.cluster_info) {
Ok(meta) => self.ns_or_default_with_reindex(ns, move |ns| {
ns.policy.update_server_authz(name, meta)
}),
Err(error) => tracing::error!(%error, "Illegal server authorization update"),
}
}
fn delete(&mut self, ns: String, name: String) {
let _span = info_span!("delete", %ns, %name).entered();
self.ns_with_reindex(ns, |ns| {
ns.policy.server_authorizations.remove(&name).is_some()
})
}
fn reset(
&mut self,
sazs: Vec<k8s::policy::ServerAuthorization>,
deleted: HashMap<String, HashSet<String>>,
) {
let _span = info_span!("reset");
// Aggregate all of the updates by namespace so that we only reindex
// once per namespace.
type Ns = NsUpdate<String, server_authorization::ServerAuthz>;
let mut updates_by_ns = HashMap::<String, Ns>::default();
for saz in sazs.into_iter() {
let namespace = saz
.namespace()
.expect("serverauthorization must be namespaced");
let name = saz.name_unchecked();
match server_authorization::ServerAuthz::from_resource(saz, &self.cluster_info) {
Ok(saz) => updates_by_ns
.entry(namespace)
.or_default()
.added
.push((name, saz)),
Err(error) => {
tracing::error!(ns = %namespace, %name, %error, "Illegal server authorization update")
}
}
}
for (ns, names) in deleted.into_iter() {
updates_by_ns.entry(ns).or_default().removed = names;
}
for (namespace, Ns { added, removed }) in updates_by_ns.into_iter() {
if added.is_empty() {
// If there are no live resources in the namespace, we do not
// want to create a default namespace instance, we just want to
// clear out all resources for the namespace (and then drop the
// whole namespace, if necessary).
self.ns_with_reindex(namespace, |ns| {
ns.policy.server_authorizations.clear();
true
});
} else {
// Otherwise, we take greater care to reindex only when the
// state actually changed. The vast majority of resets will see
// no actual data change.
self.ns_or_default_with_reindex(namespace, |ns| {
let mut changed = !removed.is_empty();
for name in removed.into_iter() {
ns.policy.server_authorizations.remove(&name);
}
for (name, saz) in added.into_iter() {
changed = ns.policy.update_server_authz(name, saz) || changed;
}
changed
});
}
}
}
}
impl kubert::index::IndexNamespacedResource<k8s::policy::AuthorizationPolicy> for Index {
fn apply(&mut self, policy: k8s::policy::AuthorizationPolicy) {
let ns = policy.namespace().unwrap();
let name = policy.name_unchecked();
let _span = info_span!("apply", %ns, saz = %name).entered();
let spec = match authorization_policy::Spec::try_from(policy.spec) {
Ok(spec) => spec,
Err(error) => {
tracing::warn!(%error, "Invalid authorization policy");
return;
}
};
self.ns_or_default_with_reindex(ns, |ns| ns.policy.update_authz_policy(name, spec))
}
fn delete(&mut self, ns: String, ap: String) {
let _span = info_span!("delete", %ns, %ap).entered();
tracing::trace!(name = %ap, "Delete");
self.ns_with_reindex(ns, |ns| {
ns.policy.authorization_policies.remove(&ap).is_some()
})
}
fn reset(
&mut self,
policies: Vec<k8s::policy::AuthorizationPolicy>,
deleted: HashMap<String, HashSet<String>>,
) {
let _span = info_span!("reset");
tracing::trace!(?deleted, ?policies, "Reset");
// Aggregate all of the updates by namespace so that we only reindex
// once per namespace.
type Ns = NsUpdate<String, authorization_policy::Spec>;
let mut updates_by_ns = HashMap::<String, Ns>::default();
for policy in policies.into_iter() {
let namespace = policy
.namespace()
.expect("authorizationpolicy must be namespaced");
let name = policy.name_unchecked();
match authorization_policy::Spec::try_from(policy.spec) {
Ok(spec) => updates_by_ns
.entry(namespace)
.or_default()
.added
.push((name, spec)),
Err(error) => {
tracing::error!(ns = %namespace, %name, %error, "Illegal server authorization update")
}
}
}
for (ns, names) in deleted.into_iter() {
updates_by_ns.entry(ns).or_default().removed = names;
}
for (namespace, Ns { added, removed }) in updates_by_ns.into_iter() {
if added.is_empty() {
// If there are no live resources in the namespace, we do not
// want to create a default namespace instance, we just want to
// clear out all resources for the namespace (and then drop the
// whole namespace, if necessary).
self.ns_with_reindex(namespace, |ns| {
ns.policy.authorization_policies.clear();
true
});
} else {
// Otherwise, we take greater care to reindex only when the
// state actually changed. The vast majority of resets will see
// no actual data change.
self.ns_or_default_with_reindex(namespace, |ns| {
let mut changed = !removed.is_empty();
for name in removed.into_iter() {
ns.policy.authorization_policies.remove(&name);
}
for (name, spec) in added.into_iter() {
changed = ns.policy.update_authz_policy(name, spec) || changed;
}
changed
});
}
}
}
}
impl kubert::index::IndexNamespacedResource<k8s::policy::MeshTLSAuthentication> for Index {
fn apply(&mut self, authn: k8s::policy::MeshTLSAuthentication) {
let ns = authn
.namespace()
.expect("MeshTLSAuthentication must have a namespace");
let name = authn.name_unchecked();
let _span = info_span!("apply", %ns, %name).entered();
let spec = match meshtls_authentication::Spec::try_from_resource(authn, &self.cluster_info)
{
Ok(spec) => spec,
Err(error) => {
tracing::warn!(%error, "Invalid MeshTLSAuthentication");
return;
}
};
if self.authentications.update_meshtls(ns, name, spec) {
self.reindex_all();
}
}
fn delete(&mut self, ns: String, name: String) {
let _span = info_span!("delete", %ns, %name).entered();
if let Entry::Occupied(mut ns) = self.authentications.by_ns.entry(ns) {
tracing::debug!("Deleting MeshTLSAuthentication");
ns.get_mut().network.remove(&name);
if ns.get().is_empty() {
ns.remove();
}
self.reindex_all();
} else {
tracing::warn!("Namespace already deleted!");
}
}
fn reset(
&mut self,
authns: Vec<k8s::policy::MeshTLSAuthentication>,
deleted: HashMap<String, HashSet<String>>,
) {
let _span = info_span!("reset");
let mut changed = false;
for authn in authns.into_iter() {
let namespace = authn
.namespace()
.expect("meshtlsauthentication must be namespaced");
let name = authn.name_unchecked();
let spec = match meshtls_authentication::Spec::try_from_resource(
authn,
&self.cluster_info,
) {
Ok(spec) => spec,
Err(error) => {
tracing::warn!(ns = %namespace, %name, %error, "Invalid MeshTLSAuthentication");
continue;
}
};
changed = self.authentications.update_meshtls(namespace, name, spec) || changed;
}
for (namespace, names) in deleted.into_iter() {
if let Entry::Occupied(mut ns) = self.authentications.by_ns.entry(namespace) {
for name in names.into_iter() {
ns.get_mut().meshtls.remove(&name);
}
if ns.get().is_empty() {
ns.remove();
}
}
}
if changed {
self.reindex_all();
}
}
}
impl kubert::index::IndexNamespacedResource<k8s::policy::NetworkAuthentication> for Index {
fn apply(&mut self, authn: k8s::policy::NetworkAuthentication) {
let ns = authn.namespace().unwrap();
let name = authn.name_unchecked();
let _span = info_span!("apply", %ns, %name).entered();
let spec = match network_authentication::Spec::try_from(authn.spec) {
Ok(spec) => spec,
Err(error) => {
tracing::warn!(%error, "Invalid NetworkAuthentication");
return;
}
};
if self.authentications.update_network(ns, name, spec) {
self.reindex_all();
}
}
fn delete(&mut self, ns: String, name: String) {
let _span = info_span!("delete", %ns, %name).entered();
if let Entry::Occupied(mut ns) = self.authentications.by_ns.entry(ns) {
tracing::debug!("Deleting MeshTLSAuthentication");
ns.get_mut().network.remove(&name);
if ns.get().is_empty() {
ns.remove();
}
self.reindex_all();
} else {
tracing::warn!("Namespace already deleted!");
}
}
fn reset(
&mut self,
authns: Vec<k8s::policy::NetworkAuthentication>,
deleted: HashMap<String, HashSet<String>>,
) {
let _span = info_span!("reset");
let mut changed = false;
for authn in authns.into_iter() {
let namespace = authn
.namespace()
.expect("meshtlsauthentication must be namespaced");
let name = authn.name_unchecked();
let spec = match network_authentication::Spec::try_from(authn.spec) {
Ok(spec) => spec,
Err(error) => {
tracing::warn!(ns = %namespace, %name, %error, "Invalid NetworkAuthentication");
return;
}
};
changed = self.authentications.update_network(namespace, name, spec) || changed;
}
for (namespace, names) in deleted.into_iter() {
if let Entry::Occupied(mut ns) = self.authentications.by_ns.entry(namespace) {
for name in names.into_iter() {
ns.get_mut().meshtls.remove(&name);
}
if ns.get().is_empty() {
ns.remove();
}
}
}
if changed {
self.reindex_all();
}
}
}
impl kubert::index::IndexNamespacedResource<k8s::policy::HttpLocalRateLimitPolicy> for Index {
fn apply(&mut self, policy: k8s::policy::HttpLocalRateLimitPolicy) {
let ns = policy.namespace().unwrap();
let name = policy.name_unchecked();
let _span = info_span!("apply", %ns, saz = %name).entered();
let spec = match ratelimit_policy::Spec::try_from(policy) {
Ok(spec) => spec,
Err(error) => {
tracing::warn!(%error, "Invalid rate limit policy");
return;
}
};
self.ns_or_default_with_reindex(ns, |ns| ns.policy.update_ratelimit_policy(name, spec))
}
fn delete(&mut self, ns: String, ap: String) {
let _span = info_span!("delete", %ns, %ap).entered();
tracing::trace!(name = %ap, "Delete");
self.ns_with_reindex(ns, |ns| ns.policy.ratelimit_policies.remove(&ap).is_some())
}
fn reset(
&mut self,
policies: Vec<k8s::policy::HttpLocalRateLimitPolicy>,
deleted: HashMap<String, HashSet<String>>,
) {
let _span = info_span!("reset");
tracing::trace!(?deleted, ?policies, "Reset");
// Aggregate all of the updates by namespace so that we only reindex
// once per namespace.
type Ns = NsUpdate<String, ratelimit_policy::Spec>;
let mut updates_by_ns = HashMap::<String, Ns>::default();
for policy in policies.into_iter() {
let namespace = policy
.namespace()
.expect("ratelimitolicy must be namespaced");
let name = policy.name_unchecked();
match ratelimit_policy::Spec::try_from(policy) {
Ok(spec) => updates_by_ns
.entry(namespace)
.or_default()
.added
.push((name, spec)),
Err(error) => {
tracing::error!(ns = %namespace, %name, %error, "Illegal server ratelimit update")
}
}
}
for (ns, names) in deleted.into_iter() {
updates_by_ns.entry(ns).or_default().removed = names;
}
for (namespace, Ns { added, removed }) in updates_by_ns.into_iter() {
if added.is_empty() {
// If there are no live resources in the namespace, we do not
// want to create a default namespace instance, we just want to
// clear out all resources for the namespace (and then drop the