Repository navigation
Expand file tree
/
Copy pathvalidate-chart.sh
More file actions
executable file
·1972 lines (1813 loc) · 107 KB
/
Copy pathvalidate-chart.sh
File metadata and controls
executable file
·1972 lines (1813 loc) · 107 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
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
# Rende il chart per ogni profilo e verifica le invarianti che, se violate,
# fanno fallire l'installazione o la lasciano a metà. Serve perché nessun altro
# controllo guarda il chart: fino a qui gli errori si scoprivano applicandoli a
# un cluster, cioè quando qualcuno stava già installando.
#
# Uso: scripts/validate-chart.sh
# Da: radice del repo. Richiede helm e python3 con PyYAML.
#
# Nota su cosa NON copre: le regole che solo l'API server conosce (un percorso
# di Ingress deve essere assoluto, un nome deve stare nei 63 caratteri) qui sono
# riprodotte a mano. La verifica completa è `kubectl apply --dry-run=server` su
# un cluster usa-e-getta, che gira in CI.
set -euo pipefail
CHART="infra/helm/pa-webinar"
OUT="$(mktemp -d)"
trap 'rm -rf "$OUT"' EXIT
fallimenti=0
errore() {
printf ' ✗ %s\n' "$1"
fallimenti=$((fallimenti + 1))
}
# I sottocharts non sono versionati (`*.tgz` è ignorato da git): senza di loro
# ogni resa fallisce, e il messaggio di helm non dice cosa fare.
if [ ! -d "$CHART/charts" ] || [ -z "$(ls -A "$CHART/charts" 2>/dev/null)" ]; then
echo "Mancano i sottocharts. Scaricali con:"
echo " helm repo add bitnami https://charts.bitnami.com/bitnami"
echo " helm repo add jitsi-contrib https://jitsi-contrib.github.io/jitsi-helm/"
echo " helm dependency build $CHART"
exit 1
fi
# Le invarianti sui Secret sono scritte in Python: senza interprete o senza
# PyYAML passerebbero a vuoto, e uno script che non può controllare niente non
# deve dire "chart valido". Meglio fermarsi qui, dove il motivo è leggibile.
if ! python3 -c 'import yaml' 2>/dev/null; then
echo "Serve python3 con PyYAML per verificare le invarianti sui Secret."
echo " pip install pyyaml (oppure: dnf install python3-pyyaml)"
exit 1
fi
# Segreti fittizi, della forma giusta: le guardie dell'applicazione rifiutano i
# valori che sembrano segnaposto, quindi non possono essere stringhe qualsiasi.
# Le password XMPP interne della conferenza sono fissate come farebbe chi
# installa: values-production.yaml (jitsi.requirePinnedCredentials) si rifiuta
# di rendere senza, gli altri profili le elencherebbero nelle note come da
# controllare.
comuni=(
--set "secrets.generate.APP_SECRET=$(openssl rand -hex 32)"
--set "secrets.generate.JITSI_JWT_SECRET=$(openssl rand -hex 32)"
--set "secrets.generate.PII_ENCRYPTION_KEY=$(openssl rand -hex 32)"
--set "secrets.generate.CRON_API_KEY=$(openssl rand -hex 32)"
--set "secrets.generate.ADMIN_API_KEY=$(openssl rand -hex 32)"
--set "secrets.generate.POSTGRES_PASSWORD=$(openssl rand -hex 24)"
--set "secrets.generate.POSTGRES_ADMIN_PASSWORD=$(openssl rand -hex 24)"
--set "secrets.generate.REDIS_PASSWORD=$(openssl rand -hex 24)"
--set "jitsi-meet.jicofo.xmpp.password=$(openssl rand -hex 16)"
--set "jitsi-meet.jvb.xmpp.password=$(openssl rand -hex 16)"
--set "jitsi-meet.jibri.xmpp.password=$(openssl rand -hex 16)"
--set "jitsi-meet.jibri.recorder.password=$(openssl rand -hex 16)"
)
segreto_jwt="$(openssl rand -hex 32)"
# nome:file di valori. I profili con un suffisso aggiungono gli argomenti di
# `argomenti_profilo`: la NetworkPolicy accesa, un controller diverso da
# ingress-nginx, Jitsi esterno, i segreti da External Secrets, k3s in sede,
# minikube per la valutazione.
profili=(
"predefinito:"
"semplice:$CHART/examples/values-simple.yaml"
"standard:$CHART/examples/values-standard.yaml"
"completo:$CHART/examples/values-full.yaml"
"produzione:$CHART/values-production.yaml"
"produzione-generica:$CHART/values-prod.yaml"
"sviluppo:$CHART/values-dev.yaml"
"semplice-rete:$CHART/examples/values-simple.yaml"
"semplice-traefik:$CHART/examples/values-simple.yaml"
"k3s:$CHART/examples/values-simple.yaml"
"semplice-minikube:$CHART/examples/values-simple.yaml"
"produzione-rete:$CHART/values-production.yaml"
"completo-segreti-esterni:$CHART/examples/values-full.yaml"
"jitsi-esterno:"
"completo-keda:$CHART/examples/values-full.yaml"
"semplice-ca:$CHART/examples/values-simple.yaml"
"aks:$CHART/examples/values-full.yaml"
"eks:$CHART/examples/values-full.yaml"
"gke:$CHART/examples/values-full.yaml"
"k3s-sito:$CHART/examples/values-simple.yaml"
"semplice-sito:$CHART/examples/values-simple.yaml"
"minikube-sito:$CHART/examples/values-simple.yaml"
"semplice-backup:$CHART/examples/values-simple.yaml"
"k3s-componenti:$CHART/examples/values-simple.yaml"
"k3s-addon:$CHART/examples/values-simple.yaml"
"sottotitoli-spenti:$CHART/examples/values-full.yaml"
"postprod:$CHART/examples/values-full.yaml"
"postprod-mt:$CHART/examples/values-full.yaml"
"postprod-senza-cpu:$CHART/examples/values-full.yaml"
"ponte-tutte-le-voci:$CHART/examples/values-simple.yaml"
"ponte-cascata:$CHART/examples/values-full.yaml"
)
# Il file di una singola installazione k3s come lo scrive chi la automatizza:
# segreti in Secret creati fuori dal chart (modalità existing), i due nomi in
# site.*, certificati dal risolutore ACME di Traefik, copia del database
# accesa, immagini costruite in proprio.
cat >"$OUT/sito-k3s.yaml" <<'FINE'
site:
portalHost: webinar.ente.example
conferenceHost: meet.ente.example
secrets:
mode: existing
existingSecretName: pa-webinar-secrets
datastoreSecretName: pa-webinar-datastore
jitsiJwtSecretName: ""
postgresql:
auth:
existingSecret: pa-webinar-datastore
redis:
auth:
existingSecret: pa-webinar-datastore
app:
image: { repository: pa-webinar, tag: local-0123456789ab, pullPolicy: Never }
migration:
image: { repository: pa-webinar, tag: local-0123456789ab-migrate, pullPolicy: Never }
ingress:
annotations:
traefik.ingress.kubernetes.io/router.tls: "true"
traefik.ingress.kubernetes.io/router.tls.certresolver: pa-webinar
tls: [ {} ]
jitsi:
conferenceIngress:
annotations:
traefik.ingress.kubernetes.io/router.tls: "true"
traefik.ingress.kubernetes.io/router.tls.certresolver: pa-webinar
tls: [ {} ]
jitsi-meet:
publicURL: https://meet.ente.example
prosody:
jwt:
existingSecretName: pa-webinar-jitsi-jwt
jicofo:
xmpp:
existingSecretName: pa-webinar-jicofo-xmpp
jvb:
xmpp:
existingSecretName: pa-webinar-jvb-xmpp
backup:
enabled: true
FINE
# I file che scrivono infra/onprem/k3s/addons/storage.sh e turn.sh nella loro
# cartella di stato, con la stessa forma: passati dopo gli esempi, completano
# lo storage e il TURN di un server k3s.
cat >"$OUT/addon-storage.yaml" <<'FINE'
app:
env:
STORAGE_FILES_S3_ENDPOINT: "https://s3.ente.example"
RECORDING_S3_ENDPOINT: "https://s3.ente.example"
FINE
cat >"$OUT/addon-turn.yaml" <<'FINE'
jitsi-meet:
turnHost: turn.ente.example
coturn:
extraEnvs:
REAL_EXTERNAL_IP: "203.0.113.10"
staticAuth:
existingSecretName: videocall-turn
allowedPeerIPs:
- "10.42.0.0-10.42.0.255"
- "203.0.113.10"
prosody:
extraEnvs:
TURNS_HOST: turn.ente.example
FINE
argomenti_profilo() {
case "$1" in
# I valori predefiniti e questi file non dicono dove sta il segreto JWT
# della conferenza, e il chart giustamente si rifiuta di rendere: qui lo
# si passa come fa chi installa.
predefinito|produzione|produzione-generica|sviluppo|produzione-rete)
printf '%s\n' --set "jitsi-meet.prosody.jwt.secret=$segreto_jwt" ;;
esac
case "$1" in
*-rete|semplice-traefik) printf '%s\n' --set networkPolicy.enabled=true ;;
esac
case "$1" in
semplice-traefik)
printf '%s\n' \
--set ingress.className=traefik \
--set jitsi-meet.web.ingress.ingressClassName=traefik \
--set 'networkPolicy.ingress.fromNamespaceSelectors[0].kubernetes\.io/metadata\.name=kube-system' ;;
completo-segreti-esterni)
printf '%s\n' \
--set secrets.mode=external \
--set secrets.jitsiJwtSecretName=videocall-jitsi-jwt ;;
jitsi-esterno)
printf '%s\n' --set jitsi.enabled=false ;;
# Il profilo per k3s in sede (infra/onprem/k3s) sopra al semplice: si
# regge su un'annotazione annullata, sul filtro delle annotazioni per le
# classi diverse da nginx e sull'immagine web del sottochart.
k3s)
printf '%s\n' -f "$CHART/examples/values-k3s.yaml" ;;
# Il profilo di scripts/minikube-up.sh sopra al semplice: immagine web del
# sottochart con un tag nullo, sonda del bridge, credenziali XMPP
# pretese (qui arrivano da `comuni`, come dal file dei segreti).
semplice-minikube)
printf '%s\n' -f "$CHART/examples/values-minikube.yaml" ;;
# Bridge scalati da KEDA al posto del CronJob (examples/keda-jvb-scaler.yaml):
# niente scaler reso, quindi il ciclo di vita tocca al suo CronJob, e
# nessun tetto fisso dei bridge.
completo-keda)
printf '%s\n' --set jvbScaler.enabled=false --set-string app.env.JVB_SCALER_ENABLED=true ;;
# Un'autorità di certificazione interna da un ConfigMap.
semplice-ca)
printf '%s\n' --set app.extraCaCerts.configMapName=ente-ca --set app.extraCaCerts.key=ca.crt ;;
# I profili dei cloud sopra al completo, senza i valori che escono da
# tofu: si rendono, e le invarianti valgono anche per loro.
aks|eks|gke)
printf '%s\n' -f "$CHART/examples/values-$1.yaml" ;;
k3s-sito)
printf '%s\n' -f "$CHART/examples/values-k3s.yaml" -f "$OUT/sito-k3s.yaml" ;;
# I nomi da site.* con l'Ingress della conferenza reso dal sottochart, i
# cui host (e publicURL) si scrivono uguali.
semplice-sito)
printf '%s\n' \
--set site.portalHost=webinar.ente.example --set site.conferenceHost=meet.ente.example \
--set jitsi-meet.publicURL=https://meet.ente.example \
--set 'jitsi-meet.web.ingress.hosts[0].host=meet.ente.example' \
--set 'jitsi-meet.web.ingress.hosts[0].paths[0]=/' \
--set 'jitsi-meet.web.ingress.tls[0].secretName=jitsi-tls' \
--set 'jitsi-meet.web.ingress.tls[0].hosts[0]=meet.ente.example' \
--set 'ingress.tls[0].secretName=portal-tls' ;;
# Come li scrive scripts/minikube-up.sh.
minikube-sito)
printf '%s\n' -f "$CHART/examples/values-minikube.yaml" \
--set site.portalHost=app.192.0.2.10.nip.io --set site.conferenceHost=jitsi.192.0.2.10.nip.io \
--set jitsi-meet.publicURL=https://jitsi.192.0.2.10.nip.io \
--set 'ingress.tls[0].secretName=app-tls' \
--set 'jitsi.conferenceIngress.tls[0].secretName=jitsi-tls' ;;
# Il server k3s con i componenti facoltativi (object storage, TURN) sopra
# al file dell'installazione, quando i loro file di valori ci sono.
k3s-componenti)
printf '%s\n' -f "$CHART/examples/values-k3s.yaml" -f "$OUT/sito-k3s.yaml"
for componente in storage turn; do
if [ -f "$CHART/examples/values-k3s-$componente.yaml" ]; then
printf '%s\n' -f "$CHART/examples/values-k3s-$componente.yaml"
fi
done
# Gli esempi degli addon si completano con il file che il loro script
# scrive nella cartella di stato: il TURN senza il suo non si rende.
for componente in storage turn; do
if [ -f "$CHART/examples/values-k3s-$componente.yaml" ] && [ -f "$OUT/addon-$componente.yaml" ]; then
printf '%s\n' -f "$OUT/addon-$componente.yaml"
fi
done ;;
# Storage e TURN di un server k3s nell'ordine in cui li passa chi
# installa: gli esempi, il file del sito, i file della cartella di stato.
k3s-addon)
printf '%s\n' -f "$CHART/examples/values-k3s.yaml" \
-f "$CHART/examples/values-k3s-storage.yaml" -f "$CHART/examples/values-k3s-turn.yaml" \
-f "$OUT/sito-k3s.yaml" -f "$OUT/addon-storage.yaml" -f "$OUT/addon-turn.yaml" ;;
# Il profilo completo con il segreto fra Jicofo e il gateway dei
# sottotitoli: deve arrivare uguale a entrambi.
completo)
printf '%s\n' --set global.captions.bridgeToken=segreto-di-prova ;;
# I sottotitoli live spenti sul profilo completo, con la NetworkPolicy:
# niente servizio, niente indirizzo in Jicofo, niente regole verso di lui.
sottotitoli-spenti)
printf '%s\n' --set global.captions.enabled=false --set networkPolicy.enabled=true ;;
# La copia del database su un volume già presente, senza NetworkPolicy.
semplice-backup)
printf '%s\n' --set backup.enabled=true --set backup.persistence.existingClaim=copie-db --set backup.retention=3 ;;
# La post-produzione AI, che nessun altro profilo rende: con vLLM acceso
# a richiesta, con il motore di traduzione su CPU e la NetworkPolicy, e
# senza il worker senza GPU.
postprod)
printf '%s\n' --set postprod.enabled=true --set postprod.vllm.autoscale=true ;;
postprod-mt)
printf '%s\n' --set postprod.enabled=true --set postprod.vllm.autoscale=true \
--set postprod.mt.enabled=true --set networkPolicy.enabled=true ;;
postprod-senza-cpu)
printf '%s\n' --set postprod.enabled=true --set postprod.worker.cpu.enabled=false ;;
# Il bridge che inoltra ogni voce, e quello con tre voci e la cascata fra
# bridge (Octo): il portale deve saperlo come lo sa il bridge.
ponte-tutte-le-voci)
printf '%s\n' --set global.jvb.numLoudest=0 ;;
ponte-cascata)
printf '%s\n' --set global.jvb.numLoudest=3 --set jitsi-meet.octo.enabled=true ;;
esac
}
# I moduli Prosody del progetto esistono in due copie: quella che monta lo
# stack Docker Compose e quella che il chart mette nel proprio ConfigMap (un
# chart non legge file fuori dalla sua cartella). Devono restare identiche.
for modulo in mod_token_affiliation_custom.lua mod_pa_media_lock.lua mod_pa_captions.lua mod_pa_occupants.lua; do
if ! cmp -s "infra/jitsi/prosody-plugins/$modulo" "$CHART/files/prosody-plugins/$modulo"; then
errore "infra/jitsi/prosody-plugins/$modulo e $CHART/files/prosody-plugins/$modulo sono diversi: aggiorna la copia del chart"
fi
done
# Lo stack Docker Compose usa il rilascio di Jitsi del chart: Prosody, Jicofo
# e il bridge con lo stesso tag, la parte web con l'immagine originale dello
# stesso rilascio (il chart usa quella patchata, con un suffisso). Nel chart la
# versione si legge come la guardia pa-webinar.validateJitsiVersions: digest
# tolto, tag mobili per quello che sono, una forma diversa non confrontata (lo
# si dice), un tag vuoto come la versione del sottochart. Compose usa solo le
# immagini pubbliche di Jitsi: un suo tag che la guardia non saprebbe leggere
# (refuso, variabile, solo digest) è un errore.
if ! python3 - docker-compose.yml "$CHART" >"$OUT/compose-jitsi.err" 2>"$OUT/compose-jitsi.note" <<'PY'
import functools
import os
import re
import sys
import tarfile
import yaml
servizi = yaml.safe_load(open(sys.argv[1])).get("services") or {}
chart = sys.argv[2]
jitsi = yaml.safe_load(open(f"{chart}/values.yaml")).get("jitsi-meet") or {}
def versione(tag):
tag = str(tag).split("@", 1)[0]
if tag in ("stable", "unstable", "latest"):
return tag
trovata = re.match(r"^(stable|unstable)-[0-9]+", tag)
return trovata.group(0) if trovata else None
@functools.cache
def versione_sottochart():
# Il sottochart che Helm usa: l'archivio della versione nel Chart.lock;
# senza, una copia spacchettata. Se non si trova, None.
try:
bloccate = (yaml.safe_load(open(f"{chart}/Chart.lock")) or {}).get("dependencies") or []
versione_chart = next((d.get("version") for d in bloccate if d.get("name") == "jitsi-meet"), None)
archivio = f"{chart}/charts/jitsi-meet-{versione_chart}.tgz"
if versione_chart and os.path.exists(archivio):
with tarfile.open(archivio) as tgz:
return (yaml.safe_load(tgz.extractfile("jitsi-meet/Chart.yaml")) or {}).get("appVersion")
except (OSError, KeyError, tarfile.TarError, yaml.YAMLError):
pass
try:
return (yaml.safe_load(open(f"{chart}/charts/jitsi-meet/Chart.yaml")) or {}).get("appVersion")
except (OSError, yaml.YAMLError):
return None
def tag_compose(immagine):
nome = immagine.split("@", 1)[0].split("/")[-1]
if ":" in nome:
return nome.rsplit(":", 1)[1]
return None if "@" in immagine else "latest"
problemi = []
saltati = []
for servizio, componente in (("jitsi-web", "web"), ("prosody", "prosody"), ("jicofo", "jicofo"), ("jvb", "jvb")):
immagine = (servizi.get(servizio) or {}).get("image")
if not immagine:
problemi.append(f"{servizio}: nessuna immagine nel servizio")
continue
tag = tag_compose(immagine)
trovata = versione(tag) if tag else None
if not trovata:
problemi.append(f"{servizio}: il tag di {immagine} non dice il rilascio di Jitsi")
continue
tag_chart = ((jitsi.get(componente) or {}).get("image") or {}).get("tag") or versione_sottochart()
attesa = versione(tag_chart) if tag_chart else None
if not attesa:
saltati.append(f"{servizio} (chart: {tag_chart or 'versione del sottochart sconosciuta'})")
elif attesa != trovata:
problemi.append(f"{servizio}={tag} (chart: {tag_chart})")
if saltati:
print("confronto con Compose saltato per " + ", ".join(saltati), file=sys.stderr)
if problemi:
print(", ".join(problemi))
sys.exit(1)
PY
then
errore "docker-compose.yml non usa il rilascio di Jitsi del chart: $(cat "$OUT/compose-jitsi.err" "$OUT/compose-jitsi.note")"
fi
[ -s "$OUT/compose-jitsi.note" ] && sed 's/^/ /' "$OUT/compose-jitsi.note"
echo "helm lint"
# Con i soli valori predefiniti la resa si ferma alla guardia sul segreto JWT
# della conferenza, e il lint non guarderebbe gli altri template.
helm lint "$CHART" --set "jitsi-meet.prosody.jwt.secret=$segreto_jwt" >/dev/null 2>"$OUT/lint.err" \
|| errore "helm lint fallisce: $(head -3 "$OUT/lint.err" | tr '\n' ' ')"
# Una guardia che scatta durante il lint non lo fa fallire: Helm la registra
# come messaggio informativo e esce con 0. Il testo cambia fra le versioni
# (Helm 3: `[INFO] Fail: …`, Helm 4: `funcMap fail`), quindi si cercano
# entrambi.
guardia_lint='\[INFO\] Fail:|funcMap fail'
if grep -qE "$guardia_lint" "$OUT/lint.err"; then
errore "helm lint si ferma a una guardia: $(grep -m1 -E "$guardia_lint" "$OUT/lint.err" | cut -c1-200)"
fi
for voce in "${profili[@]}"; do
nome="${voce%%:*}"
file="${voce#*:}"
reso="$OUT/$nome.yaml"
args=(template videocall "$CHART" -n videocall "${comuni[@]}")
[ -n "$file" ] && args+=(-f "$file")
mapfile -t extra < <(argomenti_profilo "$nome")
[ "${#extra[@]}" -gt 0 ] && args+=("${extra[@]}")
echo "profilo: $nome"
if ! helm "${args[@]}" >"$reso" 2>"$OUT/$nome.err"; then
errore "non si rende: $(head -3 "$OUT/$nome.err" | tr '\n' ' ')"
continue
fi
# Un percorso di Ingress deve essere assoluto. Il caso che è già successo:
# `paths` scritto come mappa dove il sottochart si aspetta una stringa, che
# rende `map[path:/ pathType:Prefix]` — accettato da YAML, rifiutato all'apply.
while read -r percorso; do
case "$percorso" in
/*) ;;
"") ;;
*) errore "percorso di Ingress non assoluto: $percorso" ;;
esac
done < <(awk '/^kind: Ingress$/,/^---$/' "$reso" | sed -n 's/^ *- *path: *//p')
# Un riferimento a immagine non risolto lascia i pod in ImagePullBackOff.
while read -r riga; do
[ -n "$riga" ] && errore "immagine vuota: $riga"
done < <(grep -nE '^[[:space:]]+image: *("")?$' "$reso" || true)
# In modalità "generate" i Secret resi devono bastare a far partire lo stack.
# Non basta che una chiave esista da qualche parte: deve stare nel Secret che
# quel componente monta davvero. Separare le password dei datastore senza
# ripuntare i sottochart è un errore che si vede solo così.
if ! python3 - "$reso" >"$OUT/$nome.sec" 2>"$OUT/$nome.sec.err" <<'PY'
import re
import sys
import yaml
docs = [d for d in yaml.safe_load_all(open(sys.argv[1])) if d]
segreti = {
d["metadata"]["name"]: set((d.get("stringData") or d.get("data") or {}).keys())
for d in docs if d.get("kind") == "Secret"
}
if not segreti:
sys.exit(0)
def cerca(nodo, chiave):
"""Tutti i valori associati a `chiave`, a qualsiasi profondità."""
if isinstance(nodo, dict):
for k, v in nodo.items():
if k == chiave and isinstance(v, str):
yield v
else:
yield from cerca(v, chiave)
elif isinstance(nodo, list):
for v in nodo:
yield from cerca(v, chiave)
# Il Secret dell'applicazione: quello che il Deployment monta con envFrom.
# Se il chart lo rende, la resa è in modalità "generate" e si può affermare che
# un Secret assente dai manifesti non esisterà. Nelle altre modalità i Secret
# sono creati fuori dal chart per disegno, e la stessa inferenza sarebbe falsa.
genera = False
for d in docs:
if d.get("kind") != "Deployment" or "pa-webinar" not in d["metadata"]["name"]:
continue
for c in d["spec"]["template"]["spec"].get("containers", []):
for f in c.get("envFrom", []):
nome = (f.get("secretRef") or {}).get("name")
if nome in segreti:
genera = True
mancanti = {"DATABASE_URL", "APP_SECRET", "PII_ENCRYPTION_KEY",
"ADMIN_API_KEY", "CRON_API_KEY"} - segreti[nome]
for k in sorted(mancanti):
print(f"il Secret dell'applicazione ({nome}) non ha {k}")
# I datastore: si guarda il Secret che il loro pod monta per davvero.
attesi = {"postgresql": ["POSTGRES_PASSWORD", "POSTGRES_ADMIN_PASSWORD"],
"redis": ["REDIS_PASSWORD"]}
for d in docs:
if d.get("kind") not in ("StatefulSet", "Deployment"):
continue
nome = d["metadata"]["name"]
quale = next((k for k in attesi if k in nome), None)
if not quale:
continue
montati = {n for n in cerca(d["spec"]["template"]["spec"], "secretName")}
for n in sorted(montati):
if n not in segreti:
# Il caso speculare: il sottochart punta a un Secret che nessun
# template rende. I manifesti restano validi e l'apply riesce; il
# pod resta in ContainerCreating, staccato dalla causa.
if genera:
print(f"{quale} monta il Secret {n}, che nessun template rende")
continue
for k in attesi[quale]:
if k not in segreti[n]:
print(f"{quale} monta il Secret {n}, che non contiene {k}")
# L'indirizzo della banca dati deve puntare a un Service che esiste davvero.
# Un host sbagliato non è un errore di resa né di apply: si manifesta come pod
# che non parte, senza che niente dica quale valore è stato calcolato.
servizi = {d["metadata"]["name"] for d in docs if d.get("kind") == "Service"}
for d in docs:
if d.get("kind") != "Secret":
continue
url = (d.get("stringData") or {}).get("DATABASE_URL", "")
trovato = re.match(r"postgresql://[^@]*@([^:/?]+)", url)
if not trovato:
continue
host = trovato.group(1)
# Un host con un punto è un FQDN o un database gestito fuori dal cluster:
# non deve corrispondere a niente di reso qui.
if "." in host or host in servizi:
continue
print(f"DATABASE_URL punta all'host {host!r}, che non è un Service reso")
def nome_breve(host):
"""Il nome del Service dentro un indirizzo, anche se è un FQDN di cluster."""
if host.endswith(".svc.cluster.local"):
return host.split(".", 1)[0]
return None if "." in host else host
# Stessa invariante per Redis, che però l'applicazione riceve come variabile
# d'ambiente del Deployment e non dentro un Secret. È lo stesso difetto di
# DATABASE_URL — un host scritto a mano che ignora gli override del sottochart
# — e merita lo stesso controllo.
for d in docs:
if d.get("kind") != "Deployment":
continue
for c in d["spec"]["template"]["spec"].get("containers") or []:
# `env:` puo' essere reso come chiave nulla, non solo assente.
for e in c.get("env") or []:
if e.get("name") != "REDIS_URL":
continue
trovato = re.match(r"redis://[^@]*@([^:/?]+)", str(e.get("value", "")))
if not trovato:
continue
breve = nome_breve(trovato.group(1))
if breve is None or breve in servizi:
continue
print(f"REDIS_URL punta all'host {breve!r}, che non è un Service reso")
PY
then
errore "controllo dei Secret non eseguito su $nome: $(head -3 "$OUT/$nome.sec.err" | tr '\n' ' ')"
fi
while read -r problema; do
[ -n "$problema" ] && errore "$problema"
done <"$OUT/$nome.sec"
# Invarianti che si vedono solo su un cluster, con un controller diverso da
# ingress-nginx o con la NetworkPolicy accesa: qui si riproducono sui
# manifesti resi.
if ! python3 - "$reso" "$CHART/values.yaml" >"$OUT/$nome.net" 2>"$OUT/$nome.net.err" <<'PY'
import re
import sys
import yaml
docs = [d for d in yaml.safe_load_all(open(sys.argv[1])) if d]
# Le classi che il chart tratta come controller diversi da ingress-nginx.
altri_controller = set((yaml.safe_load(open(sys.argv[2])).get("ingress") or {}).get("nonNginxClassNames") or [])
def modelli():
"""(tipo, nome, modello di pod) di ogni carico di lavoro reso."""
for d in docs:
tipo, spec = d.get("kind"), d.get("spec") or {}
if tipo in ("Deployment", "StatefulSet", "DaemonSet", "Job"):
yield tipo, d["metadata"]["name"], spec.get("template") or {}
elif tipo == "CronJob":
job = (spec.get("jobTemplate") or {}).get("spec") or {}
yield tipo, d["metadata"]["name"], job.get("template") or {}
def etichette(modello):
return (modello.get("metadata") or {}).get("labels") or {}
def seleziona(selettore, et):
for k, v in (selettore.get("matchLabels") or {}).items():
if str(et.get(k)) != str(v):
return False
for e in selettore.get("matchExpressions") or []:
k, op, valori = e["key"], e["operator"], e.get("values") or []
if op == "In" and et.get(k) not in valori:
return False
if op == "NotIn" and et.get(k) in valori:
return False
if op == "Exists" and k not in et:
return False
if op == "DoesNotExist" and k in et:
return False
return True
def ammette(regola, et, porta):
"""La regola di ingresso lascia passare un pod dello stesso namespace?"""
porte = regola.get("ports")
if porte and not any(p.get("port") in (porta, "http") for p in porte):
return False
fonti = regola.get("from")
if not fonti:
return True
for f in fonti:
if f.get("namespaceSelector") or "ipBlock" in f:
continue
if "podSelector" in f and seleziona(f["podSelector"] or {}, et):
return True
return False
carichi = list(modelli())
deployment = {n for t, n, _ in carichi if t == "Deployment"}
servizi = {d["metadata"]["name"] for d in docs if d.get("kind") == "Service"}
# Ingress: l'API server rifiuta un Ingress la cui annotazione di classe non
# coincide con ingressClassName, e un controller che non è ingress-nginx
# ignora in silenzio le annotazioni di ingress-nginx.
for d in docs:
if d.get("kind") != "Ingress":
continue
nome = d["metadata"]["name"]
classe = (d.get("spec") or {}).get("ingressClassName")
ann = d["metadata"].get("annotations") or {}
legacy = ann.get("kubernetes.io/ingress.class")
if classe and legacy is not None and legacy != classe:
print(f"l'Ingress {nome} ha classe {classe!r} e annotazione di classe {legacy!r}: l'API server lo rifiuta")
if classe in altri_controller and any(k.startswith("nginx.ingress.kubernetes.io/") for k in ann):
print(f"l'Ingress {nome} ha classe {classe!r} ma annotazioni di ingress-nginx, che non avrebbero effetto")
# NetworkPolicy del chart: deve selezionare il Deployment dell'applicazione e
# solo quello (gli altri pod parlano con l'API server, i bridge, la GPU), e
# lasciar entrare sulla porta 3000 ogni CronJob e Jibri, che a fine
# registrazione chiama l'applicazione.
for pol in docs:
if pol.get("kind") != "NetworkPolicy":
continue
if not str((pol["metadata"].get("labels") or {}).get("helm.sh/chart", "")).startswith("pa-webinar-"):
continue
nome = pol["metadata"]["name"]
spec = pol.get("spec") or {}
selettore = spec.get("podSelector") or {}
# La policy dei pod della copia del database: nessuno entra, si esce solo
# verso DNS e PostgreSQL, e deve selezionare proprio quei pod.
if (pol["metadata"].get("labels") or {}).get("app.kubernetes.io/component") == "backup":
copie = [(t, n) for t, n, m in carichi if etichette(m).get("app.kubernetes.io/component") == "backup"]
if not copie:
print(f"la NetworkPolicy {nome} è resa ma non c'è nessun CronJob della copia del database")
for t, n, m in carichi:
sel = seleziona(selettore, etichette(m))
if etichette(m).get("app.kubernetes.io/component") == "backup" and not sel:
print(f"la NetworkPolicy {nome} non seleziona {t}/{n}")
if sel and etichette(m).get("app.kubernetes.io/component") != "backup":
print(f"la NetworkPolicy {nome} seleziona anche {t}/{n}")
if spec.get("ingress"):
print(f"la NetworkPolicy {nome} lascia entrare traffico nei pod della copia del database")
porte = {p.get("port") for r in spec.get("egress") or [] for p in r.get("ports") or []}
if not {53, 5432} <= porte or porte - {53, 5432}:
print(f"la NetworkPolicy {nome} dovrebbe lasciar uscire solo DNS e PostgreSQL (53, 5432), non {sorted(porte)}")
if any(not r.get("to") for r in spec.get("egress") or []):
print(f"la NetworkPolicy {nome} ha una regola di uscita senza destinazione")
continue
# La policy dei pod di Jibri: entra solo l'applicazione, solo sull'API
# HTTP (2222), che avvia e ferma registrazioni senza autenticazione.
if (pol["metadata"].get("labels") or {}).get("app.kubernetes.io/component") == "jibri":
for t, n, m in carichi:
sel = seleziona(selettore, etichette(m))
di_jibri = etichette(m).get("app.kubernetes.io/component") == "jibri"
if di_jibri and not sel:
print(f"la NetworkPolicy {nome} non seleziona {t}/{n}")
if sel and not di_jibri:
print(f"la NetworkPolicy {nome} seleziona anche {t}/{n}")
if not any(t == "Deployment" and etichette(m).get("app.kubernetes.io/component") == "jibri" for t, n, m in carichi):
print(f"la NetworkPolicy {nome} è resa ma Jibri no")
app_j = next((m for t, n, m in carichi if t == "Deployment"
and "app.kubernetes.io/component" not in etichette(m)
and etichette(m).get("app.kubernetes.io/name") == "pa-webinar"), None)
regole = spec.get("ingress") or []
if app_j is not None and not any(ammette(r, etichette(app_j), 2222) for r in regole):
print(f"la NetworkPolicy {nome} non lascia all'applicazione la salute di Jibri (2222)")
if any(not r.get("from") for r in regole):
print(f"la NetworkPolicy {nome} ha una regola di ingresso senza sorgente: Jibri resterebbe aperto a tutti")
porte = {p.get("port") for r in regole for p in r.get("ports") or []}
if porte != {2222}:
print(f"la NetworkPolicy {nome} dovrebbe ammettere solo la porta 2222, non {sorted(porte)}")
if "Egress" in (spec.get("policyTypes") or []):
print(f"la NetworkPolicy {nome} limita l'uscita di Jibri, che apre le sue connessioni verso Prosody, la conferenza e lo storage")
continue
# La policy dei sottotitoli live: entrano solo i bridge della release
# (l'audio) e l'applicazione (lo stato), sulla 8080; escono DNS,
# l'applicazione (il contesto della stanza) e HTTPS (il modello).
if (pol["metadata"].get("labels") or {}).get("app.kubernetes.io/component") == "captions":
for t, n, m in carichi:
sel = seleziona(selettore, etichette(m))
dei_sottotitoli = etichette(m).get("app.kubernetes.io/component") == "captions"
if dei_sottotitoli and not sel:
print(f"la NetworkPolicy {nome} non seleziona {t}/{n}")
if sel and not dei_sottotitoli:
print(f"la NetworkPolicy {nome} seleziona anche {t}/{n}")
if not any(t == "Deployment" and etichette(m).get("app.kubernetes.io/component") == "captions" for t, n, m in carichi):
print(f"la NetworkPolicy {nome} è resa ma il servizio dei sottotitoli no")
istanza_c = (selettore.get("matchLabels") or {}).get("app.kubernetes.io/instance")
regole = spec.get("ingress") or []
if any(not r.get("from") for r in regole):
print(f"la NetworkPolicy {nome} ha una regola di ingresso senza sorgente: i sottotitoli resterebbero aperti a tutti")
porte = {p.get("port") for r in regole for p in r.get("ports") or []}
if porte != {8080}:
print(f"la NetworkPolicy {nome} dovrebbe ammettere solo la porta 8080, non {sorted(porte)}")
for t, n, m in carichi:
et = etichette(m)
if et.get("app.kubernetes.io/component") == "jvb" and et.get("app.kubernetes.io/instance") == istanza_c \
and not any(ammette(r, et, 8080) for r in regole):
print(f"{t}/{n}: il bridge non raggiungerebbe i sottotitoli, la NetworkPolicy {nome} non lo ammette sulla 8080")
app_c = next((m for t, n, m in carichi if t == "Deployment"
and "app.kubernetes.io/component" not in etichette(m)
and etichette(m).get("app.kubernetes.io/name") == "pa-webinar"), None)
if app_c is not None and not any(ammette(r, etichette(app_c), 8080) for r in regole):
print(f"la NetworkPolicy {nome} non lascia all'applicazione lo stato dei sottotitoli (8080)")
uscite = spec.get("egress") or []
porte_u = {p.get("port") for r in uscite for p in r.get("ports") or []}
if not {53, 3000, 443} <= porte_u:
print(f"la NetworkPolicy {nome} dovrebbe lasciar uscire DNS, l'applicazione e HTTPS (53, 3000, 443), non {sorted(porte_u)}")
if app_c is not None and not any(
any(p.get("port") == 3000 for p in r.get("ports") or [])
and any("podSelector" in d and "namespaceSelector" not in d and seleziona(d["podSelector"] or {}, etichette(app_c))
for d in r.get("to") or [])
for r in uscite):
print(f"la NetworkPolicy {nome} non lascia ai sottotitoli il contesto della stanza chiesto all'applicazione (3000)")
continue
# La policy del motore di traduzione su CPU: entra solo il worker senza
# GPU, sulla 8080 (il motore non ha autenticazione); escono DNS e HTTPS
# (il modello).
if (pol["metadata"].get("labels") or {}).get("app.kubernetes.io/component") == "postprod-mt":
for t, n, m in carichi:
sel = seleziona(selettore, etichette(m))
del_motore = etichette(m).get("app.kubernetes.io/component") == "postprod-mt"
if del_motore and not sel:
print(f"la NetworkPolicy {nome} non seleziona {t}/{n}")
if sel and not del_motore:
print(f"la NetworkPolicy {nome} seleziona anche {t}/{n}")
regole = spec.get("ingress") or []
if any(not r.get("from") for r in regole):
print(f"la NetworkPolicy {nome} ha una regola di ingresso senza sorgente: il motore resterebbe aperto a tutti")
porte = {p.get("port") for r in regole for p in r.get("ports") or []}
if porte != {8080}:
print(f"la NetworkPolicy {nome} dovrebbe ammettere solo la porta 8080, non {sorted(porte)}")
for t, n, m in carichi:
componente_m = etichette(m).get("app.kubernetes.io/component")
ammesso = any(ammette(r, etichette(m), 8080) for r in regole)
if componente_m == "postprod-worker-cpu" and not ammesso:
print(f"{t}/{n}: il worker senza GPU non raggiungerebbe il motore di traduzione, la NetworkPolicy {nome} non lo ammette sulla 8080")
if componente_m not in ("postprod-worker-cpu", "postprod-mt") and ammesso:
print(f"la NetworkPolicy {nome} lascia entrare nel motore di traduzione anche {t}/{n}")
porte_u = {p.get("port") for r in spec.get("egress") or [] for p in r.get("ports") or []}
if not {53, 443} <= porte_u:
print(f"la NetworkPolicy {nome} dovrebbe lasciar uscire DNS e HTTPS (53, 443), non {sorted(porte_u)}")
continue
if not any(t == "Deployment" and n == nome and seleziona(selettore, etichette(m)) for t, n, m in carichi):
print(f"la NetworkPolicy {nome} non seleziona il Deployment dell'applicazione, che resterebbe senza restrizioni")
for tipo, n, modello in carichi:
if seleziona(selettore, etichette(modello)) and not (tipo == "Deployment" and n == nome):
print(f"la NetworkPolicy {nome} seleziona anche {tipo}/{n}, di cui non descrive il traffico")
istanza = (selettore.get("matchLabels") or {}).get("app.kubernetes.io/instance")
della_release = {"matchLabels": {k: v for k, v in (selettore.get("matchLabels") or {}).items()
if k != "app.kubernetes.io/component"}}
for tipo, n, modello in carichi:
et = etichette(modello)
cron = tipo == "CronJob" and seleziona(della_release, et)
jibri = et.get("app.kubernetes.io/component") == "jibri" and et.get("app.kubernetes.io/instance") == istanza
sottotitoli = et.get("app.kubernetes.io/component") == "captions" and et.get("app.kubernetes.io/instance") == istanza
if not (cron or jibri or sottotitoli):
continue
if not any(ammette(r, et, 3000) for r in spec.get("ingress") or []):
print(f"{tipo}/{n} non raggiungerebbe l'applicazione: la NetworkPolicy {nome} non lo ammette sulla porta 3000")
# Con la NetworkPolicy accesa, i pod della copia del database hanno la loro.
# (Il sottochart PostgreSQL rende NetworkPolicy sue: contano solo quelle del chart.)
del_chart_np = [d for d in docs if d.get("kind") == "NetworkPolicy"
and str((d["metadata"].get("labels") or {}).get("helm.sh/chart", "")).startswith("pa-webinar-")]
if del_chart_np:
copie = {n for t, n, m in carichi if etichette(m).get("app.kubernetes.io/component") == "backup"}
coperte = [d for d in del_chart_np
if (d["metadata"].get("labels") or {}).get("app.kubernetes.io/component") == "backup"]
if copie and not coperte:
print(f"NetworkPolicy accesa ma nessuna policy per i pod della copia del database ({', '.join(sorted(copie))})")
sottotitoli = {n for t, n, m in carichi if etichette(m).get("app.kubernetes.io/component") == "captions"}
if sottotitoli and not any((d["metadata"].get("labels") or {}).get("app.kubernetes.io/component") == "captions"
for d in del_chart_np):
print(f"NetworkPolicy accesa ma nessuna policy per i pod dei sottotitoli ({', '.join(sorted(sottotitoli))})")
motore = {n for t, n, m in carichi if etichette(m).get("app.kubernetes.io/component") == "postprod-mt"}
if motore and not any((d["metadata"].get("labels") or {}).get("app.kubernetes.io/component") == "postprod-mt"
for d in del_chart_np):
print(f"NetworkPolicy accesa ma nessuna policy per i pod del motore di traduzione ({', '.join(sorted(motore))})")
# Lo scaler dei bridge con un nome esplicito deve trovare quel Deployment:
# altrimenti legge zero repliche, `kubectl scale` fallisce e con
# `replicaCount: 0` nessun bridge parte mai.
for tipo, n, modello in carichi:
if tipo != "CronJob":
continue
for c in (modello.get("spec") or {}).get("containers") or []:
testo = " ".join(str(x) for x in (c.get("command") or []) + (c.get("args") or []))
trovato = re.search(r'JVB_DEPLOY="([^"$]+)"', testo)
if trovato and trovato.group(1) not in deployment:
print(f"lo scaler cerca il Deployment {trovato.group(1)!r}, che non è reso")
# Gli indirizzi interni dell'applicazione (JVB_HEALTH_URL e gli altri) sono
# controllati più sotto, con le invarianti della conferenza.
# Bitnami pubblica nel registro pubblico solo `latest`, che cambia contenuto:
# un tag con la versione non esiste (ImagePullBackOff), e `latest` senza
# digest porta un nodo nuovo su una versione diversa dagli altri.
for tipo, n, modello in carichi:
spec = modello.get("spec") or {}
for c in (spec.get("containers") or []) + (spec.get("initContainers") or []):
immagine = str(c.get("image", ""))
if re.search(r"(^|/)bitnami/", immagine) and "@sha256:" not in immagine:
print(f"{tipo}/{n}: l'immagine {immagine} non è fissata per digest")
PY
then
errore "controllo di rete e immagini non eseguito su $nome: $(head -3 "$OUT/$nome.net.err" | tr '\n' ' ')"
fi
while read -r problema; do
[ -n "$problema" ] && errore "$problema"
done <"$OUT/$nome.net"
# La conferenza e il ciclo di vita: indirizzi interni che l'applicazione
# interroga, ruoli nella sala, chi porta avanti gli eventi, quanti bridge il
# portale si aspetta. Tutti difetti che non fermano l'installazione e si
# vedono solo usandola: una pagina di stato rossa con le sale che
# funzionano, ospiti moderatori, eventi che non si chiudono mai.
if ! python3 - "$reso" "$nome" "$CHART" >"$OUT/$nome.conf" 2>"$OUT/$nome.conf.err" <<'PY'
import os
import re
import sys
import yaml
docs = [d for d in yaml.safe_load_all(open(sys.argv[1])) if d]
SCRIPT_FINE_REGISTRAZIONE = open(os.path.join(sys.argv[3], "files/jibri-finalize.sh")).read().strip()
profilo = sys.argv[2]
def del_chart(d):
return str((d["metadata"].get("labels") or {}).get("helm.sh/chart", "")).startswith("pa-webinar-")
def modelli():
for d in docs:
tipo, spec = d.get("kind"), d.get("spec") or {}
if tipo in ("Deployment", "StatefulSet", "DaemonSet"):
yield tipo, d["metadata"]["name"], spec.get("template") or {}, spec
elif tipo == "CronJob":
job = (spec.get("jobTemplate") or {}).get("spec") or {}
yield tipo, d["metadata"]["name"], job.get("template") or {}, spec
def seleziona(selettore, et):
return all(str(et.get(k)) == str(v) for k, v in (selettore or {}).items())
carichi = list(modelli())
servizi = {d["metadata"]["name"]: d for d in docs if d.get("kind") == "Service"}
mappe = {d["metadata"]["name"]: d.get("data") or {} for d in docs if d.get("kind") == "ConfigMap"}
# L'applicazione: il Deployment del chart senza componente, e il suo ConfigMap.
app = next((d for d in docs if d.get("kind") == "Deployment" and del_chart(d)
and "app.kubernetes.io/component" not in (d["spec"]["template"]["metadata"].get("labels") or {})), None)
if app is None:
print("nessun Deployment dell'applicazione reso")
sys.exit(0)
nome_app = app["metadata"]["name"]
contenitore = app["spec"]["template"]["spec"]["containers"][0]
variabili = dict(mappe.get(nome_app, {}))
for e in contenitore.get("env") or []:
if "value" in e:
variabili[e["name"]] = str(e["value"])
def breve(host):
"""Il nome del Service dentro un indirizzo di cluster, o None se è esterno."""
trovato = re.match(r"^([a-z0-9-]+)\.[a-z0-9-]+\.svc(\.[a-z0-9.-]+)?$", host)
if trovato:
return trovato.group(1)
return None if "." in host else host
def pod_di(servizio):
"""I modelli di pod che un Service seleziona."""
sel = (servizio.get("spec") or {}).get("selector") or {}
return [(t, n, m) for t, n, m, _ in carichi
if sel and seleziona(sel, (m.get("metadata") or {}).get("labels") or {})]
def porta_pod(servizio, porta, modello):
"""La porta del container dietro una porta del Service."""
for p in (servizio.get("spec") or {}).get("ports") or []:
if p.get("port") != porta:
continue
bersaglio = p.get("targetPort", porta)
if isinstance(bersaglio, int):
return bersaglio
for c in (modello.get("spec") or {}).get("containers") or []:
for cp in c.get("ports") or []:
if cp.get("name") == bersaglio:
return cp.get("containerPort")
return None
return False
# Ogni indirizzo interno punta a un Service reso, su una porta che il Service
# espone, e con la NetworkPolicy accesa la policy dell'applicazione deve
# lasciar passare il traffico verso quella porta dei pod: altrimenti la sonda
# scade e la pagina di stato segna un guasto che non c'è.
politica = next((d for d in docs if d.get("kind") == "NetworkPolicy" and del_chart(d)
and d["metadata"]["name"] == nome_app), None)
def uscita_ammessa(et, porta):
for regola in (politica.get("spec") or {}).get("egress") or []:
porte = regola.get("ports")
if porte and not any(p.get("port") == porta for p in porte):
continue
destinazioni = regola.get("to")
if not destinazioni:
return True
for dest in destinazioni:
if "podSelector" in dest and "namespaceSelector" not in dest \
and seleziona((dest["podSelector"] or {}).get("matchLabels") or {}, et):
return True
return False
interni = ["JVB_HEALTH_URL", "JIBRI_HEALTH_URL", "JITSI_WEB_INTERNAL_URL",
"PROSODY_INTERNAL_URL", "JICOFO_HEALTH_URL", "CAPTIONS_STATUS_URL"]
for chiave in interni:
url = variabili.get(chiave)
if not url:
continue
trovato = re.match(r"^http://([^:/]+)(?::(\d+))?", url)
if not trovato:
print(f"{chiave} non è un indirizzo http interno: {url!r}")
continue
nome_svc = breve(trovato.group(1))
if nome_svc is None:
continue
porta = int(trovato.group(2) or 80)
svc = servizi.get(nome_svc)
if svc is None:
print(f"{chiave} punta al Service {nome_svc!r}, che non è reso")
continue
pods = pod_di(svc)
if not pods:
print(f"{chiave}: il Service {nome_svc!r} non seleziona nessun pod reso")
continue
for t, n, m in pods:
cp = porta_pod(svc, porta, m)
if cp is False:
print(f"{chiave} usa la porta {porta}, che il Service {nome_svc!r} non espone")
break
if politica is not None and cp and not uscita_ammessa((m.get("metadata") or {}).get("labels") or {}, cp):
print(f"{chiave}: la NetworkPolicy {nome_app} non lascia uscire l'applicazione verso {t}/{n} sulla porta {cp}")
# Conferenza nel cluster: le sonde della pagina di stato hanno i loro indirizzi
# interni, e Jibri si interroga solo se c'è.
web = [n for n in servizi if n.endswith("-web") and any(
(m.get("metadata") or {}).get("labels", {}).get("app.kubernetes.io/component") == "web"
for _, _, m in pod_di(servizi[n]))]
jibri_reso = any(n.endswith("-jibri") for n in servizi)
if web:
for chiave in ("JITSI_WEB_INTERNAL_URL", "PROSODY_INTERNAL_URL", "JICOFO_HEALTH_URL"):
if not variabili.get(chiave):
print(f"la conferenza è nel cluster ma l'applicazione non ha {chiave}: la pagina di stato passerebbe dal nome pubblico")
if "JIBRI_HEALTH_URL" in variabili and not jibri_reso:
print(f"JIBRI_HEALTH_URL è impostato ({variabili['JIBRI_HEALTH_URL']}) ma Jibri non è reso: ogni richiesta della pagina di stato aspetterebbe un Service inesistente")
if jibri_reso and "JIBRI_HEALTH_URL" not in variabili:
print("Jibri è reso ma l'applicazione non ha JIBRI_HEALTH_URL")
# Jibri recente apre l'API di salute solo su 127.0.0.1: il portale, da un altro
# pod, la raggiunge solo se Jibri la apre su tutte le interfacce.
if jibri_reso and "JIBRI_HEALTH_URL" in variabili:
for _, nome_j, modello_j, _ in carichi:
if ((modello_j.get("metadata") or {}).get("labels") or {}).get("app.kubernetes.io/component") != "jibri":
continue
ambiente = {}
for c in (modello_j.get("spec") or {}).get("containers") or []:
for f in c.get("envFrom") or []:
ambiente.update(mappe.get((f.get("configMapRef") or {}).get("name"), {}))