-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunction.ts
More file actions
322 lines (298 loc) · 10.9 KB
/
function.ts
File metadata and controls
322 lines (298 loc) · 10.9 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
import {
RunFunctionRequest,
RunFunctionResponse,
fatal,
fromModel,
normal,
setDesiredComposedResources,
to,
getDesiredComposedResources,
getDesiredCompositeResource,
getObservedCompositeResource,
getObservedComposedResources,
getCondition,
hasCapability,
Capability,
type FunctionHandler,
type Logger,
} from '@crossplane-org/function-sdk-typescript';
import { Service, ServiceAccount } from 'kubernetes-models/v1';
import { Deployment } from 'kubernetes-models/apps/v1';
import { Ingress } from 'kubernetes-models/networking.k8s.io/v1';
/**
* Ingress path configuration
*/
interface IngressPath {
path: string;
pathType?: string;
}
/**
* Ingress host configuration
*/
interface IngressHost {
host: string;
paths: IngressPath[];
}
/**
* Ingress TLS configuration
*/
interface IngressTLS {
secretName: string;
hosts: string[];
}
/**
* Function is a sample implementation showing how to use the SDK
*/
export class Function implements FunctionHandler {
// Note: This implementation is currently synchronous. When adding async operations
// (e.g., API calls, database queries), use await with those operations.
// eslint-disable-next-line @typescript-eslint/require-await
async RunFunction(req: RunFunctionRequest, logger?: Logger): Promise<RunFunctionResponse> {
const startTime = Date.now();
// Set up a minimal response from the request
let rsp = to(req);
try {
// Example: Check Crossplane capabilities
// hasCapability() allows checking what features are supported by the Crossplane version
// Starting with 2.2.0 Crossplane added the ability to download schemas.
const capabilities = {
requiredResources: hasCapability(req, Capability.CAPABILITY_REQUIRED_RESOURCES),
requiredSchemas: hasCapability(req, Capability.CAPABILITY_REQUIRED_SCHEMAS),
};
logger?.info({ capabilities }, 'Crossplane capabilities detected');
// Get our Observed Composite
const observedComposite = getObservedCompositeResource(req);
logger?.debug({ observedComposite }, 'Observed composite resource');
// Get our Desired Composite
const desiredComposite = getDesiredCompositeResource(req);
logger?.debug({ desiredComposite }, 'Desired composite resource');
// List the Desired Composed resources
const desiredComposed = getDesiredComposedResources(req);
// Extract parameters from XR spec
const name = observedComposite?.resource?.metadata?.name;
if (!name) {
fatal(rsp, 'Composite resource name is required');
return rsp;
}
const params = observedComposite?.resource?.spec?.parameters || {};
const deploymentConfig = params.deployment || {};
const imageConfig = deploymentConfig.image || {};
const serviceConfig = params.service || {};
const ingressConfig = params.ingress || {};
const serviceAccountConfig = params.serviceAccount || {};
// Common metadata for all resources
const commonMetadata = {
labels: {
'app.kubernetes.io/name': name,
'app.kubernetes.io/instance': name,
'app.kubernetes.io/managed-by': 'crossplane',
},
};
// Create ServiceAccount if enabled
if (serviceAccountConfig.create) {
const serviceAccount = new ServiceAccount({
metadata: {
...commonMetadata,
name: serviceAccountConfig.name || name,
annotations: {
...(serviceAccountConfig.annotations || {}),
},
},
automountServiceAccountToken: serviceAccountConfig.automount ?? true,
});
desiredComposed['serviceaccount'] = fromModel(serviceAccount);
}
// Create Service if config is provided
if (serviceConfig && Object.keys(serviceConfig).length > 0) {
const service = new Service({
metadata: {
...commonMetadata,
},
spec: {
type: serviceConfig.type || 'ClusterIP',
ports: [
{
port: serviceConfig.port || 80,
targetPort: 'http',
protocol: 'TCP',
name: 'http',
},
],
selector: {
'app.kubernetes.io/name': name,
'app.kubernetes.io/instance': name,
},
},
});
desiredComposed['service'] = fromModel(service);
}
const deployment = new Deployment({
metadata: {
...commonMetadata,
annotations: {
...(deploymentConfig.podAnnotations || {}),
},
},
spec: {
replicas: deploymentConfig.replicaCount || 1,
selector: {
matchLabels: {
'app.kubernetes.io/name': name,
'app.kubernetes.io/instance': name,
},
},
template: {
metadata: {
labels: {
'app.kubernetes.io/name': name,
'app.kubernetes.io/instance': name,
...(deploymentConfig.podLabels && deploymentConfig.podLabels),
},
...(deploymentConfig.podAnnotations && {
annotations: deploymentConfig.podAnnotations,
}),
},
spec: {
...((serviceAccountConfig.create === true || serviceAccountConfig.name) && {
serviceAccountName: serviceAccountConfig.name || name,
}),
...(deploymentConfig.podSecurityContext && {
securityContext: deploymentConfig.podSecurityContext,
}),
...(deploymentConfig.nodeSelector && {
nodeSelector: deploymentConfig.nodeSelector,
}),
...(deploymentConfig.tolerations && {
tolerations: deploymentConfig.tolerations,
}),
...(deploymentConfig.affinity && {
affinity: deploymentConfig.affinity,
}),
...(deploymentConfig.volumes && {
volumes: deploymentConfig.volumes,
}),
containers: [
{
name: name,
image: `${imageConfig.repository || 'nginx'}:${imageConfig.tag || 'latest'}`,
imagePullPolicy: imageConfig.pullPolicy || 'IfNotPresent',
ports: [
{
name: 'http',
containerPort: serviceConfig.port || 80,
protocol: 'TCP',
},
],
...(deploymentConfig.securityContext && {
securityContext: deploymentConfig.securityContext,
}),
...(deploymentConfig.resources && {
resources: deploymentConfig.resources,
}),
...(deploymentConfig.livenessProbe && {
livenessProbe: deploymentConfig.livenessProbe,
}),
...(deploymentConfig.readinessProbe && {
readinessProbe: deploymentConfig.readinessProbe,
}),
...(deploymentConfig.volumeMounts && {
volumeMounts: deploymentConfig.volumeMounts,
}),
},
],
},
},
},
});
desiredComposed['deployment'] = fromModel(deployment);
// Example: Check the conditions of the observed deployment
// getCondition() extracts status conditions and returns "Unknown" if not found
const observedComposed = getObservedComposedResources(req);
const observedDeployment = observedComposed['deployment'];
if (observedDeployment?.resource) {
const availableCondition = getCondition(observedDeployment.resource, 'Available');
const progressingCondition = getCondition(observedDeployment.resource, 'Progressing');
logger?.info(
{
deployment: observedDeployment.resource.metadata?.name,
available: availableCondition.status,
progressing: progressingCondition.status,
},
'Deployment conditions'
);
}
// Create Ingress if config is provided
if (ingressConfig && Object.keys(ingressConfig).length > 0) {
const ingress = new Ingress({
metadata: {
...commonMetadata,
annotations: {
...(ingressConfig.annotations || {}),
},
},
spec: {
...(ingressConfig.className && {
ingressClassName: ingressConfig.className,
}),
...(ingressConfig.hosts && {
rules: ingressConfig.hosts.map((hostConfig: IngressHost) => ({
host: hostConfig.host,
http: {
paths: hostConfig.paths.map((pathConfig: IngressPath) => ({
path: pathConfig.path,
pathType: pathConfig.pathType || 'ImplementationSpecific',
backend: {
service: {
name: name,
port: {
number: serviceConfig.port || 80,
},
},
},
})),
},
})),
}),
...(ingressConfig.tls &&
ingressConfig.tls.length > 0 && {
tls: ingressConfig.tls
.map((tlsEntry: IngressTLS) => {
// Validate that hosts are present for each TLS entry
if (!tlsEntry.hosts || tlsEntry.hosts.length === 0) {
logger?.warn(
{ secretName: tlsEntry.secretName },
'TLS entry has no hosts defined, skipping'
);
return null;
}
return {
secretName: tlsEntry.secretName,
hosts: tlsEntry.hosts,
};
})
.filter((entry: IngressTLS | null) => entry !== null),
}),
},
});
desiredComposed['ingress'] = fromModel(ingress);
}
// Merge desiredComposed with existing resources using the response helper
rsp = setDesiredComposedResources(rsp, desiredComposed);
const duration = Date.now() - startTime;
logger?.info({ duration: `${duration}ms` }, 'Function completed successfully');
normal(rsp, 'processing complete');
return rsp;
} catch (error) {
const duration = Date.now() - startTime;
logger?.error(
{
error: error instanceof Error ? error.message : String(error),
duration: `${duration}ms`,
},
'Function invocation failed'
);
fatal(rsp, error instanceof Error ? error.message : String(error));
return rsp;
}
}
}