k8s_openapi_ext/ext/
service.rs1use super::*;
2
3pub trait ServiceExt: super::ResourceBuilder {
4 fn new(name: impl ToString) -> Self;
5 fn cluster_ip(
6 name: impl ToString,
7 ports: impl IntoIterator<Item = corev1::ServicePort>,
8 ) -> Self;
9 fn node_port(name: impl ToString) -> Self;
10 fn load_balancer(name: impl ToString) -> Self;
11 fn external_name(name: impl ToString, external_name: impl ToString) -> Self;
12 fn with_labels(
13 name: impl ToString,
14 labels: impl IntoIterator<Item = (impl ToString, impl ToString)>,
15 ) -> Self;
16
17 fn spec(self, spec: corev1::ServiceSpec) -> Self;
18
19 fn selector(
20 self,
21 match_labels: impl IntoIterator<Item = (impl ToString, impl ToString)>,
22 ) -> Self;
23}
24
25impl ServiceExt for corev1::Service {
26 fn new(name: impl ToString) -> Self {
27 let metadata = metadata(name);
28 Self {
29 metadata,
30 ..default()
33 }
34 }
35
36 fn cluster_ip(
37 name: impl ToString,
38 ports: impl IntoIterator<Item = corev1::ServicePort>,
39 ) -> Self {
40 let mut service = Self::with_type(name, "ClusterIP");
41 service
42 .spec_mut()
43 .ports
44 .replace(ports.into_iter().collect());
45 service
46 }
47
48 fn node_port(name: impl ToString) -> Self {
49 Self::with_type(name, "NodePort")
50 }
51
52 fn load_balancer(name: impl ToString) -> Self {
53 Self::with_type(name, "LoadBalancer")
54 }
55
56 fn external_name(name: impl ToString, external_name: impl ToString) -> Self {
57 let mut service = Self::with_type(name, "ExternalName");
58 service
59 .spec_mut()
60 .external_name
61 .replace(external_name.to_string());
62 service
63 }
64
65 fn with_labels(
66 name: impl ToString,
67 labels: impl IntoIterator<Item = (impl ToString, impl ToString)>,
68 ) -> Self {
69 Self::new(name).labels(labels)
70 }
71
72 fn spec(self, spec: corev1::ServiceSpec) -> Self {
73 Self {
74 spec: Some(spec),
75 ..self
76 }
77 }
78
79 fn selector(
80 mut self,
81 labels: impl IntoIterator<Item = (impl ToString, impl ToString)>,
82 ) -> Self {
83 let labels = labels
84 .into_iter()
85 .map(|(key, value)| (key.to_string(), value.to_string()))
86 .collect();
87 self.spec_mut().selector.replace(labels);
88 self
89 }
90}
91
92trait ServiceExtPrivate {
93 fn with_type(name: impl ToString, r#type: impl ToString) -> Self;
94}
95
96impl ServiceExtPrivate for corev1::Service {
97 fn with_type(name: impl ToString, r#type: impl ToString) -> Self {
98 let type_ = Some(r#type.to_string());
99 let spec = corev1::ServiceSpec { type_, ..default() };
100 Self::new(name).spec(spec)
101 }
102}
103
104impl HasSpec for corev1::Service {
105 type Spec = corev1::ServiceSpec;
106
107 fn spec_mut(&mut self) -> &mut Self::Spec {
108 self.spec.get_or_insert_default()
109 }
110}