forked from rancher/cluster-api-addon-provider-fleet
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfleet_addon_config.rs
More file actions
356 lines (309 loc) · 11.3 KB
/
Copy pathfleet_addon_config.rs
File metadata and controls
356 lines (309 loc) · 11.3 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
use fleet_api_rs::fleet_cluster::ClusterAgentEnvVars;
use k8s_openapi::{
api::core::v1::ObjectReference, apimachinery::pkg::apis::meta::v1::LabelSelector,
};
use kube::{
core::{ParseExpressionError, Selector},
CELSchema, CustomResource,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
pub const AGENT_NAMESPACE: &str = "fleet-addon-agent";
/// This provides a config for fleet addon functionality
#[derive(CustomResource, Deserialize, Serialize, Clone, Default, Debug, CELSchema)]
#[kube(
kind = "FleetAddonConfig",
group = "addons.cluster.x-k8s.io",
version = "v1alpha1",
status = "FleetAddonConfigStatus",
rule = Rule::new("self.metadata.name == 'fleet-addon-config'"),
)]
#[serde(rename_all = "camelCase")]
pub struct FleetAddonConfigSpec {
/// Enable clusterClass controller functionality.
///
/// This will create Fleet ClusterGroups for each ClusterClaster with the same name.
pub cluster_class: Option<ClusterClassConfig>,
/// Enable Cluster config funtionality.
///
/// This will create Fleet Cluster for each Cluster with the same name.
/// In case the cluster specifies topology.class, the name of the ClusterClass
/// will be added to the Fleet Cluster labels.
pub cluster: Option<ClusterConfig>,
// Fleet chart configuratoin options
pub config: Option<FleetConfig>,
// Fleet chart installation options
pub install: Option<FleetInstall>,
}
impl Default for FleetAddonConfig {
fn default() -> Self {
Self {
metadata: Default::default(),
spec: FleetAddonConfigSpec {
cluster_class: Some(ClusterClassConfig::default()),
cluster: Some(ClusterConfig::default()),
..Default::default()
},
status: Default::default(),
}
}
}
#[derive(Deserialize, Serialize, Clone, Default, Debug, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct FleetAddonConfigStatus {
pub installed_version: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ClusterClassConfig {
/// Setting to disable setting owner references on the created resources
#[serde(skip_serializing_if = "Option::is_none")]
pub set_owner_references: Option<bool>,
/// Allow to patch resources, maintaining the desired state.
/// If is not set, resources will only be re-created in case of removal.
#[serde(skip_serializing_if = "Option::is_none")]
pub patch_resource: Option<bool>,
}
impl Default for ClusterClassConfig {
fn default() -> Self {
Self {
patch_resource: Some(true),
set_owner_references: Some(true),
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ClusterConfig {
/// Apply a ClusterGroup for a ClusterClass referenced from a different namespace.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub apply_class_group: Option<bool>,
/// Allow to patch resources, maintaining the desired state.
/// If is not set, resources will only be re-created in case of removal.
#[serde(skip_serializing_if = "Option::is_none")]
pub patch_resource: Option<bool>,
/// Setting to disable setting owner references on the created resources
#[serde(skip_serializing_if = "Option::is_none")]
pub set_owner_references: Option<bool>,
/// Naming settings for the fleet cluster
#[serde(skip_serializing_if = "Option::is_none")]
pub naming: Option<NamingStrategy>,
/// Namespace selection for the fleet agent
#[serde(skip_serializing_if = "Option::is_none")]
pub agent_namespace: Option<String>,
/// Host network allows to deploy agent configuration using hostNetwork: true setting
/// which eludes dependency on the CNI configuration for the cluster.
#[serde(skip_serializing_if = "Option::is_none")]
pub host_network: Option<bool>,
/// AgentEnvVars are extra environment variables to be added to the agent deployment.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent_env_vars: Option<Vec<ClusterAgentEnvVars>>,
/// Import settings for the CAPI cluster. Allows to import clusters based on a set of labels,
/// set on the cluster or the namespace.
#[serde(flatten)]
pub selectors: Selectors,
#[cfg(feature = "agent-initiated")]
/// Prepare initial cluster for agent initiated connection
#[serde(skip_serializing_if = "Option::is_none")]
pub agent_initiated: Option<bool>,
}
impl ClusterConfig {
pub(crate) fn agent_install_namespace(&self) -> String {
self.agent_namespace
.clone()
.unwrap_or(AGENT_NAMESPACE.to_string())
}
#[cfg(feature = "agent-initiated")]
pub(crate) fn agent_initiated_connection(&self) -> bool {
self.agent_initiated.filter(|&set| set).is_some()
}
pub(crate) fn apply_naming(&self, name: String) -> String {
let strategy = self.naming.clone().unwrap_or_default();
strategy.apply(name.clone().into()).unwrap_or(name)
}
}
/// NamingStrategy is controlling Fleet cluster naming
#[derive(Serialize, Deserialize, Clone, Debug, JsonSchema, Default)]
pub struct NamingStrategy {
/// Specify a prefix for the Cluster name, applied to created Fleet cluster
pub prefix: Option<String>,
/// Specify a suffix for the Cluster name, applied to created Fleet cluster
pub suffix: Option<String>,
}
impl Default for ClusterConfig {
fn default() -> Self {
Self {
apply_class_group: Some(true),
set_owner_references: Some(true),
naming: Default::default(),
agent_namespace: AGENT_NAMESPACE.to_string().into(),
host_network: Some(true),
#[cfg(feature = "agent-initiated")]
agent_initiated: Some(true),
selectors: Default::default(),
patch_resource: Some(true),
agent_env_vars: None,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct FleetConfig {
pub server: Server,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct FleetInstall {
/// Chart version to install
#[serde(flatten)]
pub install_version: Install,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum Install {
/// Follow the latest version of the chart on install
FollowLatest(bool),
/// Use specific version to install
Version(String),
}
impl Default for Install {
fn default() -> Self {
Self::FollowLatest(true)
}
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum Server {
InferLocal(bool),
Custom(InstallOptions),
}
#[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct InstallOptions {
pub api_server_ca_config_ref: Option<ObjectReference>,
pub api_server_url: Option<String>,
}
impl NamingStrategy {
pub fn apply(&self, name: Option<String>) -> Option<String> {
name.map(|name| match &self.prefix {
Some(prefix) => prefix.clone() + &name,
None => name,
})
.map(|name| match &self.suffix {
Some(suffix) => name + suffix,
None => name,
})
}
}
/// Selectors is controlling Fleet import strategy settings.
#[derive(Serialize, Deserialize, Clone, Debug, JsonSchema, Default)]
#[serde(rename_all = "camelCase")]
pub struct Selectors {
/// Namespace label selector. If set, only clusters in the namespace matching label selector will be imported.
pub namespace_selector: LabelSelector,
/// Cluster label selector. If set, only clusters matching label selector will be imported.
pub selector: LabelSelector,
}
impl FleetAddonConfig {
// Raw cluster selector
pub(crate) fn cluster_selector(&self) -> Result<Selector, ParseExpressionError> {
self.spec
.cluster
.as_ref()
.map(|c| c.selectors.selector.clone())
.unwrap_or_default()
.try_into()
}
// Provide a static label selector for cluster objects, which can be always be set
// and will not cause cache events from resources in the labeled Namespace to be missed
pub(crate) fn cluster_watch(&self) -> Result<Selector, ParseExpressionError> {
Ok(self
.namespace_selector()?
.selects_all()
.then_some(self.cluster_selector()?)
.unwrap_or_default())
}
// Raw namespace selector
pub(crate) fn namespace_selector(&self) -> Result<Selector, ParseExpressionError> {
self.spec
.cluster
.as_ref()
.map(|c| c.selectors.namespace_selector.clone())
.unwrap_or_default()
.try_into()
}
// Check for general cluster operations, like create, patch, etc. Evaluates to false if disabled.
pub(crate) fn cluster_operations_enabled(&self) -> bool {
self.spec.cluster.is_some()
}
// Check for general ClusterClass operations, like create, patch, etc. Evaluates to false if disabled.
pub(crate) fn cluster_class_operations_enabled(&self) -> bool {
self.spec.cluster_class.is_some()
}
// Check for general cluster patching setting.
pub(crate) fn cluster_patch_enabled(&self) -> bool {
self.spec
.cluster
.as_ref()
.map(|c| c.patch_resource)
.unwrap_or_default()
.filter(|&enabled| enabled)
.is_some()
}
// Check for general clusterClass patching setting.
pub(crate) fn cluster_class_patch_enabled(&self) -> bool {
self.spec
.cluster_class
.as_ref()
.map(|c| c.patch_resource)
.unwrap_or_default()
.filter(|&enabled| enabled)
.is_some()
}
}
#[cfg(test)]
mod tests {
use crate::api::fleet_addon_config::NamingStrategy;
#[tokio::test]
async fn test_naming_strategy() {
assert_eq!(
Some("prefixtestsuffix".to_string()),
NamingStrategy {
prefix: "prefix".to_string().into(),
suffix: "suffix".to_string().into(),
}
.apply("test".to_string().into())
);
assert_eq!(
Some("testsuffix".to_string()),
NamingStrategy {
suffix: "suffix".to_string().into(),
..Default::default()
}
.apply("test".to_string().into())
);
assert_eq!(
Some("prefixtest".to_string()),
NamingStrategy {
prefix: "prefix".to_string().into(),
..Default::default()
}
.apply("test".to_string().into())
);
assert_eq!(
Some("test".to_string()),
NamingStrategy {
..Default::default()
}
.apply("test".to_string().into())
);
assert_eq!(
None,
NamingStrategy {
prefix: "prefix".to_string().into(),
suffix: "suffix".to_string().into(),
}
.apply(None)
);
}
}