controller 0.59.0

Tembo Operator for Postgres
Documentation
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
use crate::{apis::coredb_types::CoreDB, Context};
use crate::{errors::OperatorError, network_policies::apply_network_policy};
use k8s_openapi::api::core::v1::Service;
use k8s_openapi::api::networking::v1::NetworkPolicy;
use kube::Resource;
use kube::{
    api::{Api, Patch, PatchParams, ResourceExt},
    client::Client,
};
use serde_json::json;
use std::env;
use std::sync::Arc;
use tracing::{debug, error, info};

/// Reconcile dedicated networking resources for the CoreDB instance.
///
/// This function handles the creation, update, or deletion of Kubernetes resources
/// required for dedicated networking, including services and network policies
///
/// # Parameters
/// - `cdb`: The CoreDB custom resource instance.
/// - `ctx`: The operator context containing the Kubernetes client and other configurations.
/// - `basedomain`: The base domain for the service.
pub async fn reconcile_dedicated_networking(
    cdb: &CoreDB,
    ctx: Arc<Context>,
    basedomain: &str,
) -> Result<(), OperatorError> {
    let ns = cdb.namespace().unwrap_or_else(|| {
        error!(
            "Namespace not found for CoreDB instance: {}",
            cdb.name_any()
        );
        "default".to_string()
    });
    let client = ctx.client.clone();

    debug!(
        "Starting reconciliation of dedicated networking for CoreDB instance: {} in namespace: {}",
        cdb.name_any(),
        ns
    );

    if let Some(dedicated_networking) = &cdb.spec.dedicated_networking {
        if dedicated_networking.enabled {
            debug!(
                "Dedicated networking is enabled for CoreDB instance: {}",
                cdb.name_any()
            );

            debug!(
                "Reconciling network policies for dedicated networking in namespace: {}",
                ns
            );
            reconcile_dedicated_network_policies(cdb.clone(), client.clone(), &ns)
                .await
                .map_err(|e| {
                    error!("Failed to reconcile network policies: {:?}", e);
                    e
                })?;
            debug!(
                "Handling primary service ingress for CoreDB instance: {}",
                cdb.name_any()
            );
            reconcile_dedicated_networking_service(
                cdb,
                client.clone(),
                &ns,
                dedicated_networking.public,
                false,
                &dedicated_networking.serviceType,
                basedomain,
            )
            .await
            .map_err(|e| {
                error!("Failed to reconcile primary service ingress: {:?}", e);
                e
            })?;

            if dedicated_networking.include_standby {
                debug!(
                    "Handling standby service ingress for CoreDB instance: {}",
                    cdb.name_any()
                );
                reconcile_dedicated_networking_service(
                    cdb,
                    client.clone(),
                    &ns,
                    dedicated_networking.public,
                    true,
                    &dedicated_networking.serviceType,
                    basedomain,
                )
                .await
                .map_err(|e| {
                    error!("Failed to reconcile standby service ingress: {:?}", e);
                    e
                })?;
            } else {
                debug!(
                    "Standby service is not included. Deleting standby service for CoreDB instance: {}",
                    cdb.name_any()
                );
                delete_dedicated_networking_service(client.clone(), &ns, &cdb.name_any(), true)
                    .await
                    .map_err(|e| {
                        error!("Failed to delete standby service: {:?}", e);
                        e
                    })?;
            }

            debug!(
                "Completed reconciliation of dedicated networking for CoreDB instance: {} in namespace: {}",
                cdb.name_any(),
                ns
            );
        } else {
            debug!(
                "Dedicated networking is disabled for CoreDB instance: {}",
                cdb.name_any()
            );

            // Handling the case if dedicatedNetworking is disabled
            delete_dedicated_networking_policies(client.clone(), &ns, &cdb.name_any())
                .await
                .map_err(|e| {
                    error!("Failed to delete network policies: {:?}", e);
                    e
                })?;

            delete_dedicated_networking_service(client.clone(), &ns, &cdb.name_any(), false)
                .await
                .map_err(|e| {
                    error!("Failed to delete primary service: {:?}", e);
                    e
                })?;

            delete_dedicated_networking_service(client.clone(), &ns, &cdb.name_any(), true)
                .await
                .map_err(|e| {
                    error!("Failed to delete standby service: {:?}", e);
                    e
                })?;
        }
    } else {
        debug!(
            "Dedicated networking is not configured for CoreDB instance: {}",
            cdb.name_any()
        );

        // Handling the case even if dedicatedNetworking is not present in the spec
        delete_dedicated_networking_policies(client.clone(), &ns, &cdb.name_any())
            .await
            .map_err(|e| {
                error!("Failed to delete network policies: {:?}", e);
                e
            })?;

        delete_dedicated_networking_service(client.clone(), &ns, &cdb.name_any(), false)
            .await
            .map_err(|e| {
                error!("Failed to delete primary service: {:?}", e);
                e
            })?;

        delete_dedicated_networking_service(client.clone(), &ns, &cdb.name_any(), true)
            .await
            .map_err(|e| {
                error!("Failed to delete standby service: {:?}", e);
                e
            })?;
    }

    Ok(())
}

/// Reconcile the network policies for dedicated networking.
///
/// This function applies a specific network policy that allows traffic from a specified CIDR block
/// to the CoreDB pods.
///
/// # Parameters
/// - `cdb`: The CoreDB Spec
/// - `client`: The Kubernetes client.
/// - `namespace`: The namespace in which to apply the network policy.
async fn reconcile_dedicated_network_policies(
    cdb: CoreDB,
    client: Client,
    namespace: &str,
) -> Result<(), OperatorError> {
    let cdb_name = cdb.name_any();
    let np_api: Api<NetworkPolicy> = Api::namespaced(client, namespace);

    let cidr_list = env::var("CLOUD_LOAD_BALANCER_INTERNAL_IP_CIDR")
        .unwrap_or_else(|_| "10.0.0.0/8".to_string())
        .split(',')
        .map(|s| s.trim().to_string())
        .collect::<Vec<String>>();

    let policy_name = format!("{}-allow-nlb", cdb_name);
    debug!(
        "Applying network policy: {} in namespace: {} to allow traffic from CIDRs: {:?}",
        policy_name, namespace, cidr_list
    );

    let ingress_rules = cidr_list
        .into_iter()
        .map(|cidr| {
            serde_json::json!({
                "from": [
                    {
                        "ipBlock": {
                            "cidr": cidr
                        }
                    }
                ],
                "ports": [
                    {
                        "protocol": "TCP",
                        "port": 5432
                    }
                ]
            })
        })
        .collect::<Vec<_>>();

    let dedicated_network_policy = serde_json::json!({
        "apiVersion": "networking.k8s.io/v1",
        "kind": "NetworkPolicy",
        "metadata": {
            "name": policy_name,
            "namespace": namespace,
        },
        "spec": {
            "podSelector": {
                "matchLabels": {
                    "cnpg.io/cluster": cdb_name
                }
            },
            "policyTypes": ["Ingress"],
            "ingress": ingress_rules
        }
    });

    apply_network_policy(namespace, &np_api, dedicated_network_policy)
        .await
        .map_err(|e| {
            error!(
                "Failed to apply network policy: {} in namespace: {}. Error: {:?}",
                policy_name, namespace, e
            );
            OperatorError::NetworkPolicyError(format!("Failed to apply network policy: {:?}", e))
        })?;

    debug!(
        "Successfully applied network policy: {} in namespace: {}",
        policy_name, namespace
    );
    Ok(())
}

/// Delete the NetworkPolicy resource for dedicated networking.
///
/// This function deletes the NetworkPolicy resource associated with the CoreDB instance.
///
/// # Parameters
/// - `client`: The Kubernetes client.
/// - `namespace`: The namespace in which to delete the network policy.
/// - `cdb_name`: The name of the CoreDB instance.
async fn delete_dedicated_networking_policies(
    client: Client,
    namespace: &str,
    cdb_name: &str,
) -> Result<(), OperatorError> {
    let np_api: Api<NetworkPolicy> = Api::namespaced(client, namespace);
    let policy_name = format!("{}-allow-nlb", cdb_name);

    debug!(
        "Checking if network policy: {} exists in namespace: {} for deletion",
        policy_name, namespace
    );

    if np_api.get(&policy_name).await.is_ok() {
        info!(
            "Network policy: {} exists in namespace: {}. Proceeding with deletion.",
            policy_name, namespace
        );

        np_api
            .delete(&policy_name, &Default::default())
            .await
            .map_err(|e| {
                error!(
                    "Failed to delete network policy: {} in namespace: {}. Error: {}",
                    policy_name, namespace, e
                );
                OperatorError::NetworkPolicyError(format!(
                    "Failed to delete network policy: {:?}",
                    e
                ))
            })?;

        info!(
            "Successfully deleted network policy: {} in namespace: {}",
            policy_name, namespace
        );
    } else {
        debug!(
            "Network policy: {} does not exist in namespace: {}. Skipping deletion.",
            policy_name, namespace
        );
    }

    Ok(())
}

/// Reconcile the Service resource for dedicated networking.
///
/// This function creates or updates a Service resource for the primary or standby service
/// based on the dedicated networking configuration.
///
/// # Parameters
/// - `cdb`: The CoreDB custom resource instance.
/// - `client`: The Kubernetes client.
/// - `namespace`: The namespace in which to create or update the service.
/// - `is_public`: Whether the service is public or private.
/// - `is_standby`: Whether the service is for a standby (read-only) instance.
/// - `service_type`: The type of the Kubernetes Service (e.g., "LoadBalancer", "ClusterIP").
/// - `basedomain`: The base domain for the service.
async fn reconcile_dedicated_networking_service(
    cdb: &CoreDB,
    client: Client,
    namespace: &str,
    is_public: bool,
    is_standby: bool,
    service_type: &str,
    basedomain: &str,
) -> Result<(), OperatorError> {
    let cdb_name = &cdb.name_any();
    let owner_reference = cdb.controller_owner_ref(&()).unwrap();
    let service_name = if is_standby {
        format!("{}-dedicated-ro", cdb_name)
    } else {
        format!("{}-dedicated", cdb_name)
    };

    let lb_scheme = if is_public {
        "internet-facing"
    } else {
        "internal"
    };
    let lb_internal = if is_public { "false" } else { "true" };

    debug!(
        "Applying Service: {} in namespace: {} with type: {} and scheme: {}",
        service_name, namespace, service_type, lb_scheme
    );

    let external_dns_hostname = format!(
        "dedicated{suffix}.{namespace}.{basedomain}",
        suffix = if is_standby { "-ro" } else { "" }
    );

    let mut annotations = serde_json::Map::new();
    annotations.insert(
        "external-dns.alpha.kubernetes.io/hostname".to_string(),
        serde_json::Value::String(external_dns_hostname),
    );

    annotations.extend([
        (
            "service.beta.kubernetes.io/aws-load-balancer-internal".to_string(),
            serde_json::Value::String(lb_internal.to_string()),
        ),
        (
            "service.beta.kubernetes.io/aws-load-balancer-scheme".to_string(),
            serde_json::Value::String(lb_scheme.to_string()),
        ),
        (
            "service.beta.kubernetes.io/aws-load-balancer-nlb-target-type".to_string(),
            serde_json::Value::String("ip".to_string()),
        ),
        (
            "service.beta.kubernetes.io/aws-load-balancer-type".to_string(),
            serde_json::Value::String("nlb-ip".to_string()),
        ),
        (
            "service.beta.kubernetes.io/aws-load-balancer-healthcheck-protocol".to_string(),
            serde_json::Value::String("TCP".to_string()),
        ),
        (
            "service.beta.kubernetes.io/aws-load-balancer-healthcheck-port".to_string(),
            serde_json::Value::String("5432".to_string()),
        ),
    ]);

    let mut labels = serde_json::Map::new();
    labels.insert(
        "cnpg.io/cluster".to_string(),
        serde_json::Value::String(cdb_name.to_string()),
    );

    let mut service_spec = serde_json::Map::new();
    service_spec.insert(
        "ports".to_string(),
        json!([{
            "name": "postgres",
            "port": 5432,
            "protocol": "TCP",
            "targetPort": 5432
        }]),
    );
    service_spec.insert(
        "selector".to_string(),
        json!({
            "cnpg.io/cluster": cdb_name,
            "role": if is_standby { "replica" } else { "primary" }
        }),
    );
    service_spec.insert("sessionAffinity".to_string(), json!("None"));
    service_spec.insert("type".to_string(), json!(service_type));
    let ip_allow_list = cdb.spec.ip_allow_list.clone().unwrap_or_default();

    // Allow ip_allow_list to allow all entries are in CIDR notation
    let ip_allow_list_cidr: Vec<String> = ip_allow_list
        .iter()
        .map(|ip| {
            if ip.contains('/') {
                ip.clone()
            } else {
                format!("{}/32", ip)
            }
        })
        .collect();

    if service_type == "LoadBalancer" && !ip_allow_list_cidr.is_empty() {
        service_spec.insert(
            "loadBalancerSourceRanges".to_string(),
            json!(ip_allow_list_cidr),
        );
    }

    let service = json!({
        "apiVersion": "v1",
        "kind": "Service",
        "metadata": {
            "name": service_name,
            "namespace": namespace,
            "annotations": annotations,
            "ownerReferences": [owner_reference],
            "labels": labels
        },
        "spec": service_spec
    });

    let svc_api: Api<Service> = Api::namespaced(client, namespace);
    let patch_params = PatchParams::apply("cntrlr").force();
    let patch = Patch::Apply(&service);

    svc_api
        .patch(&service_name, &patch_params, &patch)
        .await
        .map_err(|e| {
            error!(
                "Failed to apply service: {} in namespace: {}. Error: {}",
                service_name, namespace, e
            );
            OperatorError::ServiceError(format!("Failed to apply service: {:?}", e))
        })?;

    debug!(
        "Successfully applied service: {} in namespace: {}",
        service_name, namespace
    );

    Ok(())
}

/// Delete the Service resource for dedicated networking.
///
/// This function deletes the Service resource for either the primary or standby service.
///
/// # Parameters
/// - `client`: The Kubernetes client.
/// - `namespace`: The namespace in which to delete the service.
/// - `cdb_name`: The name of the CoreDB instance.
/// - `is_standby`: Whether the service is for a standby (read-only) instance.
async fn delete_dedicated_networking_service(
    client: Client,
    namespace: &str,
    cdb_name: &str,
    is_standby: bool,
) -> Result<(), OperatorError> {
    let service_name = if is_standby {
        format!("{}-dedicated-ro", cdb_name)
    } else {
        format!("{}-dedicated", cdb_name)
    };

    let svc_api: Api<Service> = Api::namespaced(client, namespace);

    debug!(
        "Checking if service: {} exists in namespace: {} for deletion",
        service_name, namespace
    );

    if svc_api.get(&service_name).await.is_ok() {
        info!(
            "Service: {} exists in namespace: {}. Proceeding with deletion.",
            service_name, namespace
        );

        svc_api
            .delete(&service_name, &Default::default())
            .await
            .map_err(|e| {
                error!(
                    "Failed to delete service: {} in namespace: {}. Error: {}",
                    service_name, namespace, e
                );
                OperatorError::ServiceError(format!("Failed to delete service: {:?}", e))
            })?;

        info!(
            "Successfully deleted service: {} in namespace: {}",
            service_name, namespace
        );
    } else {
        debug!(
            "Service: {} does not exist in namespace: {}. Skipping deletion.",
            service_name, namespace
        );
    }

    Ok(())
}