kaniop_operator/kanidm/crd.rs
1use crate::crd::is_default;
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use k8s_openapi::api::apps::v1::StatefulSetPersistentVolumeClaimRetentionPolicy;
6use k8s_openapi::api::core::v1::{
7 Affinity, Container, EmptyDirVolumeSource, EnvVar, EphemeralVolumeSource, HostAlias,
8 PersistentVolumeClaim, PersistentVolumeClaimSpec, PodDNSConfig, PodSecurityContext,
9 ResourceRequirements, SecretKeySelector, Toleration, TopologySpreadConstraint, Volume,
10 VolumeMount,
11};
12use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector};
13use kube::CustomResource;
14use kube::api::ObjectMeta;
15#[cfg(feature = "schemars")]
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19/// Specification of the desired behavior of the Kanidm cluster. More info:
20/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
21#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default)]
22#[cfg_attr(feature = "schemars", derive(JsonSchema))]
23// workaround: '`' character is not allowed in the kube `doc` attribute during doctests
24#[cfg_attr(
25 not(doctest),
26 kube(
27 doc = r#"The `Kanidm` custom resource definition (CRD) defines a desired [Kanidm](https://kanidm.com)
28 setup to run in a Kubernetes cluster. It allows to specify many options such as the number of replicas,
29 persistent storage, and many more.
30
31 For each `Kanidm` resource, the Operator deploys one or several `StatefulSet` objects in the same namespace. The number of StatefulSets is equal to the number of replicas.
32 "#
33 )
34)]
35#[kube(
36 category = "kaniop",
37 group = "kaniop.rs",
38 version = "v1beta1",
39 kind = "Kanidm",
40 plural = "kanidms",
41 singular = "kanidm",
42 shortname = "idm",
43 namespaced,
44 status = "KanidmStatus",
45 printcolumn = r#"{"name":"Replicas","type":"string","description":"The number of replicas: ready/desired","jsonPath":".status.replicaColumn"}"#,
46 printcolumn = r#"{"name":"Domain","type":"string","jsonPath":".spec.domain"}"#,
47 printcolumn = r#"{"name":"Secret","type":"string","jsonPath":".status.secretName"}"#,
48 printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
49 derive = "Default"
50)]
51#[serde(rename_all = "camelCase")]
52pub struct KanidmSpec {
53 /// The DNS domain name of the server. This is used in a number of security-critical
54 /// contexts such as webauthn, so it *must* match your DNS hostname. It is used to
55 /// create security principal names such as `william@idm.example.com` so that in a
56 /// (future) trust configuration it is possible to have unique Security Principal
57 /// Names (spns) throughout the topology.
58 ///
59 /// This cannot be changed after creation.
60 #[schemars(extend("x-kubernetes-validations" = [{"message": "Domain cannot be changed.", "rule": "self == oldSelf"}]))]
61 #[schemars(regex(
62 pattern = r"^([a-z0-9]([-a-z0-9]*[a-z0-9])?\.)*[a-z0-9]([-a-z0-9]*[a-z0-9])?$"
63 ))]
64 pub domain: String,
65
66 /// Different group of replicas with specific configuration as role, resources, affinity rules, and more.
67 /// Each group will be deployed as a separate StatefulSet.
68 #[schemars(extend("x-kubernetes-validations" = [{"message": "At least one ReplicaGroup is required", "rule": "self.size() > 0"}]))]
69 // max is defined for allowing CEL expression in validation admission policy estimate
70 // expression costs
71 #[validate(length(min = 1, max = 100))]
72 pub replica_groups: Vec<ReplicaGroup>,
73
74 /// List of external replication nodes. This is used to configure replication between
75 /// different Kanidm clusters.
76 ///
77 /// **WARNING**: `admin` and `idm_admin` passwords are going to be reset.
78 // max is defined for allowing CEL expression in validation admission policy estimate
79 // expression costs
80 #[validate(length(max = 100))]
81 #[serde(default, skip_serializing_if = "is_default")]
82 pub external_replication_nodes: Vec<ExternalReplicationNode>,
83
84 /// Container image name. More info: https://kubernetes.io/docs/concepts/containers/images
85 /// This field is optional to allow higher level config management to default or override
86 /// container images in workload controllers like StatefulSets.
87 #[serde(default = "default_image", skip_serializing_if = "is_default")]
88 pub image: String,
89
90 /// Log level for Kanidm.
91 #[serde(default, skip_serializing_if = "is_default")]
92 pub log_level: KanidmLogLevel,
93
94 /// Port name used for the pods and governing service. Default: "https"
95 #[serde(default = "default_port_name", skip_serializing_if = "is_default")]
96 pub port_name: String,
97
98 /// Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag
99 /// is specified, or IfNotPresent otherwise. Cannot be updated.
100 /// More info: https://kubernetes.io/docs/concepts/containers/images#updating-images
101 #[serde(skip_serializing_if = "Option::is_none")]
102 pub image_pull_policy: Option<String>,
103
104 /// List of environment variables to set in the `kanidm` container.
105 /// This can be used to set Kanidm configuration options.
106 /// More info: https://kanidm.github.io/kanidm/master/server_configuration.html
107 #[serde(skip_serializing_if = "Option::is_none")]
108 pub env: Option<Vec<EnvVar>>,
109
110 /// Namespaces to match for KanidmOAuth2Clients discovery.
111 ///
112 /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
113 /// - Empty selector `{}`: matches all namespaces in the cluster
114 /// - Selector with labels: matches namespaces with matching labels
115 ///
116 /// Example for all namespaces: `oauth2ClientNamespaceSelector: {}`
117 #[serde(skip_serializing_if = "Option::is_none")]
118 pub oauth2_client_namespace_selector: Option<LabelSelector>,
119
120 /// Namespaces to match for KanidmGroups discovery.
121 ///
122 /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
123 /// - Empty selector `{}`: matches all namespaces in the cluster
124 /// - Selector with labels: matches namespaces with matching labels
125 ///
126 /// Example for all namespaces: `groupNamespaceSelector: {}`
127 #[serde(skip_serializing_if = "Option::is_none")]
128 pub group_namespace_selector: Option<LabelSelector>,
129
130 /// Namespaces to match for KanidmPersonAccounts discovery.
131 ///
132 /// - Not defined (default): matches only the current namespace where this Kanidm resource is deployed
133 /// - Empty selector `{}`: matches all namespaces in the cluster
134 /// - Selector with labels: matches namespaces with matching labels
135 ///
136 /// Example for all namespaces: `personNamespaceSelector: {}`
137 #[serde(skip_serializing_if = "Option::is_none")]
138 pub person_namespace_selector: Option<LabelSelector>,
139
140 /// StorageSpec defines the configured storage for a group Kanidm servers.
141 /// If no storage option is specified, then by default an
142 /// [EmptyDir](https://kubernetes.io/docs/concepts/storage/volumes/#emptydir) will be used.
143 ///
144 /// If multiple storage options are specified, priority will be given as follows:
145 /// 1. emptyDir
146 /// 2. ephemeral
147 /// 3. volumeClaimTemplate
148 ///
149 /// Note: Kaniop does not resize PVCs until Kubernetes fix
150 /// [KEP-4650](https://github.com/kubernetes/enhancements/pull/4651).
151 /// Although, StatefulSet will be recreated if the PVC is resized.
152 #[serde(skip_serializing_if = "Option::is_none")]
153 pub storage: Option<KanidmStorage>,
154
155 /// Defines the port name used for the LDAP service. If not defined, LDAP service will not be
156 /// configured. Service port will be `3636`.
157 ///
158 /// StartTLS is not supported due to security risks such as credential leakage and MITM attacks
159 /// that are fundamental in how StartTLS works. StartTLS can not be repaired to prevent this.
160 /// LDAPS is the only secure method of communicating to any LDAP server. Kanidm will use its
161 /// certificates for both HTTPS and LDAPS.
162 #[serde(skip_serializing_if = "Option::is_none")]
163 pub ldap_port_name: Option<String>,
164
165 /// Specifies the name of the secret holding the TLS private key and certificate for the server.
166 /// If not provided, the ingress secret will be used. The server will not start if the secret
167 /// is missing.
168 #[serde(skip_serializing_if = "Option::is_none")]
169 pub tls_secret_name: Option<String>,
170
171 /// Service defines the service configuration for the Kanidm server.
172 #[serde(skip_serializing_if = "Option::is_none")]
173 pub service: Option<KanidmService>,
174
175 /// Ingress defines the ingress configuration for the Kanidm server. Domain will be the host
176 /// for the ingress. TLS is required.
177 #[serde(skip_serializing_if = "Option::is_none")]
178 pub ingress: Option<KanidmIngress>,
179
180 /// Volumes allows the configuration of additional volumes on the output StatefulSet
181 /// definition. Volumes specified will be appended to other volumes that are generated as a
182 /// result of StorageSpec objects.
183 #[serde(skip_serializing_if = "Option::is_none")]
184 pub volumes: Option<Vec<Volume>>,
185
186 /// VolumeMounts allows the configuration of additional VolumeMounts.
187 ///
188 /// VolumeMounts will be appended to other VolumeMounts in the kanidm’ container, that are
189 /// generated as a result of StorageSpec objects.
190 #[serde(skip_serializing_if = "Option::is_none")]
191 pub volume_mounts: Option<Vec<VolumeMount>>,
192
193 /// The field controls if and how PVCs are deleted during the lifecycle of a StatefulSet.
194 /// The default behavior is all PVCs are retained.
195 /// This is a beta field from 1.27. It requires enabling the StatefulSetAutoDeletePVC feature
196 /// gate.
197 #[serde(skip_serializing_if = "Option::is_none")]
198 pub persistent_volume_claim_retention_policy:
199 Option<StatefulSetPersistentVolumeClaimRetentionPolicy>,
200
201 /// SecurityContext holds pod-level security attributes and common container settings.
202 /// This defaults to the default PodSecurityContext.
203 #[serde(skip_serializing_if = "Option::is_none")]
204 pub security_context: Option<PodSecurityContext>,
205
206 /// Defines the DNS policy for the pods.
207 #[serde(skip_serializing_if = "Option::is_none")]
208 pub dns_policy: Option<String>,
209
210 /// Defines the DNS configuration for the pods.
211 #[serde(skip_serializing_if = "Option::is_none")]
212 pub dns_config: Option<PodDNSConfig>,
213
214 /// Containers allows injecting additional containers or modifying operator generated
215 /// containers. This can be used to allow adding an authentication proxy to the Pods or to
216 /// change the behavior of an operator generated container. Containers described here modify
217 /// an operator generated container if they share the same name and modifications are done
218 /// via a strategic merge patch.
219 ///
220 /// The name of container managed by the operator is: kanidm
221 ///
222 /// Overriding containers is entirely outside the scope of what the maintainers will support
223 /// and by doing so, you accept that this behaviour may break at any time without notice.
224 #[serde(skip_serializing_if = "Option::is_none")]
225 pub containers: Option<Vec<Container>>,
226
227 /// InitContainers allows injecting initContainers to the Pod definition. Those can be used to
228 /// e.g. fetch secrets for injection into the Kanidm configuration from external sources.
229 /// Any errors during the execution of an initContainer will lead to a restart of the Pod.
230 /// More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
231 /// InitContainers described here modify an operator generated init containers if they share
232 /// the same name and modifications are done via a strategic merge patch.
233 ///
234 /// The names of init container name managed by the operator are: * init-config-reloader.
235 ///
236 /// Overriding init containers is entirely outside the scope of what the maintainers will
237 /// support and by doing so, you accept that this behaviour may break at any time without notice.
238 #[serde(skip_serializing_if = "Option::is_none")]
239 pub init_containers: Option<Vec<Container>>,
240
241 /// Minimum number of seconds for which a newly created Pod should be ready without any of its
242 /// container crashing for it to be considered available. Defaults to 0 (pod will be considered
243 /// available as soon as it is ready)
244 #[serde(skip_serializing_if = "Option::is_none")]
245 pub min_ready_seconds: Option<i32>,
246
247 /// Optional list of hosts and IPs that will be injected into the Pod’s hosts file if specified.
248 #[serde(skip_serializing_if = "Option::is_none")]
249 pub host_aliases: Option<Vec<HostAlias>>,
250
251 /// Use the host’s network namespace if true.
252 ///
253 /// Make sure to understand the security implications if you want to enable it
254 /// (https://kubernetes.io/docs/concepts/configuration/overview/).
255 ///
256 /// When hostNetwork is enabled, this will set the DNS policy to ClusterFirstWithHostNet
257 /// automatically.
258 #[serde(skip_serializing_if = "Option::is_none")]
259 pub host_network: Option<bool>,
260}
261
262#[derive(Serialize, Deserialize, Clone, Debug, Default)]
263#[cfg_attr(feature = "schemars", derive(JsonSchema))]
264#[serde(rename_all = "camelCase")]
265pub struct ReplicaGroup {
266 /// The name of the replica group.
267 pub name: String,
268
269 /// Number of replicas to deploy for a Kanidm replica group.
270 pub replicas: i32,
271
272 /// The Kanidm role of each node in the replica group.
273 #[serde(default)]
274 pub role: KanidmServerRole,
275
276 /// If true, the first pod of the StatefulSet will be considered as the primary node.
277 /// The rest of the nodes are considered as secondary nodes.
278 /// This means that if database issues occur the content of the primary will take precedence
279 /// over the rest of the nodes.
280 /// This is only valid for the WriteReplica role and can only be set to true for one
281 /// replica group or external replication node.
282 /// Defaults to false.
283 #[serde(default)]
284 pub primary_node: bool,
285
286 /// Defines the resources requests and limits of the kanidm’ container.
287 #[serde(skip_serializing_if = "Option::is_none")]
288 pub resources: Option<ResourceRequirements>,
289
290 /// Defines on which Nodes the Pods are scheduled.
291 #[serde(skip_serializing_if = "Option::is_none")]
292 pub node_selector: Option<BTreeMap<String, String>>,
293
294 /// Defines the Pods’ affinity scheduling rules if specified.
295 #[serde(skip_serializing_if = "Option::is_none")]
296 pub affinity: Option<Affinity>,
297
298 /// Defines the Pods’ tolerations if specified.
299 #[serde(skip_serializing_if = "Option::is_none")]
300 pub tolerations: Option<Vec<Toleration>>,
301
302 /// Defines the pod’s topology spread constraints if specified.
303 #[serde(skip_serializing_if = "Option::is_none")]
304 pub topology_spread_constraints: Option<Vec<TopologySpreadConstraint>>,
305}
306
307// re-implementation of kanidmd_core::config::ServerRole because it is not Serialize
308#[derive(Serialize, Deserialize, Clone, Debug, Default)]
309#[cfg_attr(feature = "schemars", derive(JsonSchema))]
310#[serde(rename_all = "snake_case")]
311pub enum KanidmServerRole {
312 /// Full read-write replica with web UI
313 #[default]
314 WriteReplica,
315 /// Read-write replica without the web UI
316 WriteReplicaNoUI,
317 /// Read-only replica for load balancing read operations
318 ReadOnlyReplica,
319}
320
321#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
322#[cfg_attr(feature = "schemars", derive(JsonSchema))]
323#[serde(rename_all = "camelCase")]
324pub struct ExternalReplicationNode {
325 /// Name of the external replication node. This just have internal use.
326 pub name: String,
327
328 /// The hostname of the external replication node.
329 pub hostname: String,
330
331 /// The replication port of the external replication node.
332 pub port: i32,
333
334 /// Defines the secret that contains the identity certificate of the external replication node.
335 pub certificate: SecretKeySelector,
336
337 /// Defines the type of replication to use. Defaults to MutualPull.
338 #[serde(default)]
339 pub _type: ReplicationType,
340
341 /// Select external replication node as the primary node. This means that if database conflicts
342 /// occur the content of the primary will take precedence over the rest of the nodes.
343 /// Note: just one external replication node or replication group can be selected as primary.
344 /// Defaults to false.
345 #[serde(default)]
346 pub automatic_refresh: bool,
347}
348
349// re-implementation of kanidmd_core::repl::config::RepNodeConfig because it is not Serialize and
350// attributes changed
351#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
352#[cfg_attr(feature = "schemars", derive(JsonSchema))]
353#[serde(rename_all = "kebab-case")]
354pub enum ReplicationType {
355 /// Both nodes can initiate replication with each other
356 #[default]
357 MutualPull,
358 /// This node allows the external node to pull changes, but won't initiate
359 AllowPull,
360 /// This node will pull changes from the external node
361 Pull,
362}
363
364fn default_image() -> String {
365 "kanidm/server:latest".to_string()
366}
367
368// re-implementation of sketching::LogLevel because it is not Serialize
369#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
370#[cfg_attr(feature = "schemars", derive(JsonSchema))]
371#[serde(rename_all = "snake_case")]
372pub enum KanidmLogLevel {
373 /// Most verbose logging level, includes all debug and info messages
374 Trace,
375 /// Debug level logging, useful for troubleshooting
376 Debug,
377 /// Standard informational logging level
378 #[default]
379 Info,
380}
381
382fn default_port_name() -> String {
383 "https".to_string()
384}
385
386/// PersistentVolumeClaimTemplate defines a PVC template with optional metadata.
387/// This allows users to specify a PVC template without requiring metadata to be explicitly set.
388#[derive(Serialize, Deserialize, Clone, Debug, Default)]
389#[cfg_attr(feature = "schemars", derive(JsonSchema))]
390#[serde(rename_all = "camelCase")]
391pub struct PersistentVolumeClaimTemplate {
392 /// Standard object's metadata. More info:
393 /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
394 #[serde(skip_serializing_if = "Option::is_none")]
395 pub metadata: Option<ObjectMeta>,
396
397 /// spec defines the desired characteristics of a volume requested by a pod author. More info:
398 /// https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
399 pub spec: Option<PersistentVolumeClaimSpec>,
400}
401
402impl PersistentVolumeClaimTemplate {
403 /// Convert this template into a k8s-openapi PersistentVolumeClaim
404 pub fn to_persistent_volume_claim(&self) -> PersistentVolumeClaim {
405 PersistentVolumeClaim {
406 metadata: self.metadata.clone().unwrap_or_default(),
407 spec: self.spec.clone(),
408 ..Default::default()
409 }
410 }
411}
412
413#[derive(Serialize, Deserialize, Clone, Debug, Default)]
414#[cfg_attr(feature = "schemars", derive(JsonSchema))]
415#[serde(rename_all = "camelCase")]
416pub struct KanidmStorage {
417 /// EmptyDirVolumeSource to be used by the StatefulSet. If specified, it takes precedence over
418 /// `ephemeral` and `volumeClaimTemplate`.
419 /// More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
420 #[serde(skip_serializing_if = "Option::is_none")]
421 pub empty_dir: Option<EmptyDirVolumeSource>,
422
423 /// EphemeralVolumeSource to be used by the StatefulSet.
424 /// More info: https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#generic-ephemeral-volumes
425 #[serde(skip_serializing_if = "Option::is_none")]
426 pub ephemeral: Option<EphemeralVolumeSource>,
427
428 /// Defines the PVC spec to be used by the Kanidm StatefulSets. The easiest way to use a volume
429 /// that cannot be automatically provisioned is to use a label selector alongside manually
430 /// created PersistentVolumes.
431 #[serde(skip_serializing_if = "Option::is_none")]
432 pub volume_claim_template: Option<PersistentVolumeClaimTemplate>,
433}
434
435#[derive(Serialize, Deserialize, Clone, Debug, Default)]
436#[cfg_attr(feature = "schemars", derive(JsonSchema))]
437#[serde(rename_all = "camelCase")]
438pub struct KanidmService {
439 /// Annotations is an unstructured key value map stored with a resource that may be set by
440 /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
441 /// be preserved when modifying objects.
442 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
443 #[serde(skip_serializing_if = "Option::is_none")]
444 pub annotations: Option<BTreeMap<String, String>>,
445
446 /// Specify the Service's type where the Kanidm Service is exposed
447 /// Please note that some Ingress controllers like https://github.com/kubernetes/ingress-gce
448 /// forces you to expose your Service on a NodePort
449 /// Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and
450 /// LoadBalancer. "ClusterIP" allocates a cluster-internal IP address for load-balancing to
451 /// endpoints. Endpoints are determined by the selector or if that is not specified, by manual
452 /// construction of an Endpoints object or EndpointSlice objects. If clusterIP is "None",
453 /// no virtual IP is allocated and the endpoints are published as a set of endpoints rather
454 /// than a virtual IP. "NodePort" builds on ClusterIP and allocates a port on every node which
455 /// routes to the same endpoints as the clusterIP. "LoadBalancer" builds on NodePort and creates
456 /// an external load-balancer (if supported in the current cloud) which routes to the same
457 /// endpoints as the clusterIP. "ExternalName" aliases this service to the specified
458 /// externalName. Several other fields do not apply to ExternalName services.
459 /// More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
460 #[serde(skip_serializing_if = "Option::is_none")]
461 pub type_: Option<String>,
462}
463
464#[derive(Serialize, Deserialize, Clone, Debug, Default)]
465#[cfg_attr(feature = "schemars", derive(JsonSchema))]
466#[serde(rename_all = "camelCase")]
467pub struct KanidmIngress {
468 /// Annotations is an unstructured key value map stored with a resource that may be set by
469 /// external tools to store and retrieve arbitrary metadata. They are not queryable and should
470 /// be preserved when modifying objects.
471 /// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations
472 #[serde(skip_serializing_if = "Option::is_none")]
473 pub annotations: Option<BTreeMap<String, String>>,
474
475 /// ingressClassName is the name of an IngressClass cluster resource. Ingress controller
476 /// implementations use this field to know whether they should be serving this Ingress resource,
477 /// by a transitive connection (controller -\> IngressClass -\> Ingress resource). Although the
478 /// `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined,
479 /// it was widely supported by Ingress controllers to create a direct binding between Ingress
480 /// controller and Ingress resources. Newly created Ingress resources should prefer using the
481 /// field. However, even though the annotation is officially deprecated, for backwards
482 /// compatibility reasons, ingress controllers should still honor that annotation if present.
483 #[serde(skip_serializing_if = "Option::is_none")]
484 pub ingress_class_name: Option<String>,
485 /// Defines the name of the secret that contains the TLS private key and certificate for the
486 /// server. If not defined, the default will be the Kanidm name appended with `-tls`.
487 #[serde(skip_serializing_if = "Option::is_none")]
488 pub tls_secret_name: Option<String>,
489 /// Additional Subject Alternative Names (SANs) to include in the TLS certificate.
490 /// The main domain from the Kanidm spec is automatically included.
491 /// This does not add additional hosts to the ingress resource, only certificate SANs.
492 #[serde(skip_serializing_if = "Option::is_none")]
493 pub extra_tls_hosts: Option<BTreeSet<String>>,
494}
495
496/// Most recent observed status of the Kanidm cluster. Read-only.
497/// More info:
498/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
499#[derive(Serialize, Deserialize, Clone, Debug, Default)]
500#[cfg_attr(feature = "schemars", derive(JsonSchema))]
501#[serde(rename_all = "camelCase")]
502pub struct KanidmStatus {
503 /// Total number of available pods (ready for at least minReadySeconds) targeted by this Kanidm
504 /// deployment.
505 pub available_replicas: i32,
506
507 #[serde(skip_serializing_if = "Option::is_none")]
508 pub conditions: Option<Vec<Condition>>,
509
510 /// Total number of non-terminated pods targeted by this Kanidm cluster.
511 pub replicas: i32,
512
513 /// Total number of unavailable pods targeted by this Kanidm cluster.
514 pub unavailable_replicas: i32,
515
516 /// Total number of non-terminated pods targeted by this Kanidm cluster that have the
517 /// desired version spec.
518 pub updated_replicas: i32,
519
520 /// Status per replica in the Kanidm cluster.
521 pub replica_statuses: Vec<KanidmReplicaStatus>,
522
523 /// Ready vs desired replicas.
524 pub replica_column: String,
525
526 /// Admin users secret name.
527 pub secret_name: Option<String>,
528}
529
530#[derive(Serialize, Deserialize, Clone, Debug)]
531#[cfg_attr(feature = "schemars", derive(JsonSchema))]
532#[serde(rename_all = "camelCase")]
533pub struct KanidmReplicaStatus {
534 /// Pod name: replica group StatefulSet name plus the pod index.
535 pub pod_name: String,
536
537 /// StatefulSet name: Kanidm name plus the replica group name.
538 pub statefulset_name: String,
539
540 /// The current state of the replica.
541 pub state: KanidmReplicaState,
542}
543
544#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
545#[cfg_attr(feature = "schemars", derive(JsonSchema))]
546#[serde(rename_all = "snake_case")]
547pub enum KanidmReplicaState {
548 Initialized,
549 Pending,
550}
551
552#[cfg(test)]
553mod tests {
554 use super::*;
555 use k8s_openapi::api::core::v1::PersistentVolumeClaimSpec;
556
557 #[test]
558 fn test_pvc_template_optional_metadata() {
559 // Test that we can create a PVC template without metadata
560 let pvc_template = PersistentVolumeClaimTemplate {
561 metadata: None,
562 spec: Some(PersistentVolumeClaimSpec::default()),
563 };
564
565 // Test that it can be converted to a k8s PVC
566 let k8s_pvc = pvc_template.to_persistent_volume_claim();
567 assert_eq!(k8s_pvc.metadata, ObjectMeta::default());
568 assert_eq!(k8s_pvc.spec, pvc_template.spec);
569 }
570
571 #[test]
572 fn test_pvc_template_with_metadata() {
573 let custom_metadata = ObjectMeta {
574 name: Some("test-pvc".to_string()),
575 labels: Some([("app".to_string(), "test".to_string())].into()),
576 ..ObjectMeta::default()
577 };
578
579 // Test that we can create a PVC template with metadata
580 let pvc_template = PersistentVolumeClaimTemplate {
581 metadata: Some(custom_metadata.clone()),
582 spec: Some(PersistentVolumeClaimSpec::default()),
583 };
584
585 // Test that it can be converted to a k8s PVC
586 let k8s_pvc = pvc_template.to_persistent_volume_claim();
587 assert_eq!(k8s_pvc.metadata, custom_metadata);
588 assert_eq!(k8s_pvc.spec, pvc_template.spec);
589 }
590}