raijin-server 0.2.24__tar.gz → 0.2.26__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of raijin-server might be problematic. Click here for more details.

Files changed (54) hide show
  1. {raijin_server-0.2.24/src/raijin_server.egg-info → raijin_server-0.2.26}/PKG-INFO +1 -1
  2. {raijin_server-0.2.24 → raijin_server-0.2.26}/setup.cfg +1 -1
  3. raijin_server-0.2.26/src/raijin_server/__init__.py +5 -0
  4. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/istio.py +4 -5
  5. raijin_server-0.2.26/src/raijin_server/modules/kong.py +334 -0
  6. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/kubernetes.py +32 -1
  7. {raijin_server-0.2.24 → raijin_server-0.2.26/src/raijin_server.egg-info}/PKG-INFO +1 -1
  8. raijin_server-0.2.24/src/raijin_server/__init__.py +0 -5
  9. raijin_server-0.2.24/src/raijin_server/modules/kong.py +0 -163
  10. {raijin_server-0.2.24 → raijin_server-0.2.26}/LICENSE +0 -0
  11. {raijin_server-0.2.24 → raijin_server-0.2.26}/README.md +0 -0
  12. {raijin_server-0.2.24 → raijin_server-0.2.26}/pyproject.toml +0 -0
  13. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/cli.py +0 -0
  14. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/config.py +0 -0
  15. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/healthchecks.py +0 -0
  16. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/__init__.py +0 -0
  17. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/apokolips_demo.py +0 -0
  18. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/bootstrap.py +0 -0
  19. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/calico.py +0 -0
  20. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/cert_manager.py +0 -0
  21. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/essentials.py +0 -0
  22. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/firewall.py +0 -0
  23. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/full_install.py +0 -0
  24. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/grafana.py +0 -0
  25. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/hardening.py +0 -0
  26. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/harness.py +0 -0
  27. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/kafka.py +0 -0
  28. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/loki.py +0 -0
  29. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/metallb.py +0 -0
  30. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/minio.py +0 -0
  31. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/network.py +0 -0
  32. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/observability_dashboards.py +0 -0
  33. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/observability_ingress.py +0 -0
  34. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/prometheus.py +0 -0
  35. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/sanitize.py +0 -0
  36. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/secrets.py +0 -0
  37. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/ssh_hardening.py +0 -0
  38. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/traefik.py +0 -0
  39. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/velero.py +0 -0
  40. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/modules/vpn.py +0 -0
  41. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/scripts/__init__.py +0 -0
  42. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/scripts/checklist.sh +0 -0
  43. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/scripts/install.sh +0 -0
  44. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/scripts/log_size_metric.sh +0 -0
  45. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/scripts/pre-deploy-check.sh +0 -0
  46. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/utils.py +0 -0
  47. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server/validators.py +0 -0
  48. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server.egg-info/SOURCES.txt +0 -0
  49. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server.egg-info/dependency_links.txt +0 -0
  50. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server.egg-info/entry_points.txt +0 -0
  51. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server.egg-info/requires.txt +0 -0
  52. {raijin_server-0.2.24 → raijin_server-0.2.26}/src/raijin_server.egg-info/top_level.txt +0 -0
  53. {raijin_server-0.2.24 → raijin_server-0.2.26}/tests/test_full_install_sequence.py +0 -0
  54. {raijin_server-0.2.24 → raijin_server-0.2.26}/tests/test_registry.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: raijin-server
3
- Version: 0.2.24
3
+ Version: 0.2.26
4
4
  Summary: CLI para automacao de setup e hardening de servidores Ubuntu Server.
5
5
  Home-page: https://example.com/raijin-server
6
6
  Author: Equipe Raijin
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = raijin-server
3
- version = 0.2.24
3
+ version = 0.2.26
4
4
  description = CLI para automacao de setup e hardening de servidores Ubuntu Server.
5
5
  long_description = file: README.md
6
6
  long_description_content_type = text/markdown
@@ -0,0 +1,5 @@
1
+ """Pacote principal do CLI Raijin Server."""
2
+
3
+ __version__ = "0.2.26"
4
+
5
+ __all__ = ["__version__"]
@@ -147,6 +147,9 @@ metadata:
147
147
  namespace: istio-system
148
148
  spec:
149
149
  profile: {profile}
150
+ meshConfig:
151
+ defaultConfig:
152
+ holdApplicationUntilProxyStarts: true
150
153
  components:
151
154
  pilot:
152
155
  enabled: true
@@ -175,20 +178,16 @@ spec:
175
178
  kubernetes.io/hostname: {node_name}
176
179
  service:
177
180
  type: {service_type}
178
- values:
179
- global:
180
- proxy:
181
- holdApplicationUntilProxyStarts: true
182
181
  """
183
182
 
184
183
  config_path = Path("/tmp/raijin-istio-config.yaml")
185
184
  write_file(config_path, istio_config, ctx)
186
185
 
187
186
  # Instala usando o arquivo de configuração
187
+ # Nota: istioctl não tem --timeout, ele usa readiness probes internamente
188
188
  install_cmd = [
189
189
  "istioctl", "install",
190
190
  "-f", str(config_path),
191
- "--timeout", "10m",
192
191
  "-y",
193
192
  ]
194
193
 
@@ -0,0 +1,334 @@
1
+ """Configuracao do Kong Gateway via Helm com configuracoes production-ready."""
2
+
3
+ import socket
4
+ import time
5
+ from pathlib import Path
6
+
7
+ import typer
8
+
9
+ from raijin_server.utils import ExecutionContext, helm_upgrade_install, require_root, run_cmd, write_file
10
+
11
+
12
+ def _detect_node_name(ctx: ExecutionContext) -> str:
13
+ """Detecta nome do node para nodeSelector."""
14
+ result = run_cmd(
15
+ ["kubectl", "get", "nodes", "-o", "jsonpath={.items[0].metadata.name}"],
16
+ ctx,
17
+ check=False,
18
+ )
19
+ if result.returncode == 0 and (result.stdout or "").strip():
20
+ return (result.stdout or "").strip()
21
+ return socket.gethostname()
22
+
23
+
24
+ def _check_metallb_installed(ctx: ExecutionContext) -> bool:
25
+ """Verifica se MetalLB está instalado no cluster."""
26
+ result = run_cmd(
27
+ ["kubectl", "get", "deployment", "metallb-controller", "-n", "metallb-system"],
28
+ ctx,
29
+ check=False,
30
+ )
31
+ return result.returncode == 0
32
+
33
+
34
+ def _check_cert_manager_installed(ctx: ExecutionContext) -> bool:
35
+ """Verifica se cert-manager está instalado no cluster."""
36
+ result = run_cmd(
37
+ ["kubectl", "get", "deployment", "cert-manager", "-n", "cert-manager"],
38
+ ctx,
39
+ check=False,
40
+ )
41
+ return result.returncode == 0
42
+
43
+
44
+ def _check_existing_kong(ctx: ExecutionContext) -> bool:
45
+ """Verifica se existe instalacao do Kong."""
46
+ result = run_cmd(
47
+ ["helm", "status", "kong", "-n", "kong"],
48
+ ctx,
49
+ check=False,
50
+ )
51
+ return result.returncode == 0
52
+
53
+
54
+ def _check_orphan_crds(ctx: ExecutionContext) -> list[str]:
55
+ """Detecta CRDs orfaos do Kong (sem ownership do Helm)."""
56
+ result = run_cmd(
57
+ ["kubectl", "get", "crd", "-o", "name"],
58
+ ctx,
59
+ check=False,
60
+ )
61
+
62
+ if result.returncode != 0:
63
+ return []
64
+
65
+ kong_crds = []
66
+ for line in (result.stdout or "").strip().split("\n"):
67
+ if "konghq.com" in line:
68
+ # Extrai nome do CRD
69
+ crd_name = line.replace("customresourcedefinition.apiextensions.k8s.io/", "")
70
+ kong_crds.append(crd_name)
71
+
72
+ return kong_crds
73
+
74
+
75
+ def _cleanup_orphan_crds(ctx: ExecutionContext, crds: list[str]) -> None:
76
+ """Remove CRDs orfaos do Kong."""
77
+ typer.echo(f"Removendo {len(crds)} CRDs orfaos do Kong...")
78
+
79
+ for crd in crds:
80
+ run_cmd(
81
+ ["kubectl", "delete", "crd", crd, "--ignore-not-found"],
82
+ ctx,
83
+ check=False,
84
+ )
85
+
86
+ time.sleep(3)
87
+ typer.secho(" CRDs orfaos removidos.", fg=typer.colors.GREEN)
88
+
89
+
90
+ def _uninstall_kong(ctx: ExecutionContext) -> None:
91
+ """Remove instalacao anterior do Kong."""
92
+ typer.echo("Removendo instalacao anterior do Kong...")
93
+
94
+ run_cmd(
95
+ ["helm", "uninstall", "kong", "-n", "kong"],
96
+ ctx,
97
+ check=False,
98
+ )
99
+
100
+ run_cmd(
101
+ ["kubectl", "delete", "namespace", "kong", "--ignore-not-found"],
102
+ ctx,
103
+ check=False,
104
+ )
105
+
106
+ time.sleep(5)
107
+
108
+
109
+ def _wait_for_kong_ready(ctx: ExecutionContext, timeout: int = 180) -> bool:
110
+ """Aguarda pods do Kong ficarem Ready."""
111
+ typer.echo("Aguardando pods do Kong ficarem Ready...")
112
+ deadline = time.time() + timeout
113
+
114
+ while time.time() < deadline:
115
+ result = run_cmd(
116
+ [
117
+ "kubectl", "-n", "kong", "get", "pods",
118
+ "-o", "jsonpath={range .items[*]}{.metadata.name}={.status.phase} {end}",
119
+ ],
120
+ ctx,
121
+ check=False,
122
+ )
123
+
124
+ if result.returncode == 0:
125
+ output = (result.stdout or "").strip()
126
+ if output:
127
+ pods = []
128
+ for item in output.split():
129
+ if "=" in item:
130
+ parts = item.rsplit("=", 1)
131
+ if len(parts) == 2:
132
+ pods.append((parts[0], parts[1]))
133
+
134
+ if pods and all(phase == "Running" for _, phase in pods):
135
+ typer.secho(f" Todos os {len(pods)} pods Running.", fg=typer.colors.GREEN)
136
+ return True
137
+
138
+ pending = [name for name, phase in pods if phase != "Running"]
139
+ if pending:
140
+ typer.echo(f" Aguardando: {', '.join(pending[:3])}...")
141
+
142
+ time.sleep(10)
143
+
144
+ typer.secho(" Timeout aguardando pods do Kong.", fg=typer.colors.YELLOW)
145
+ return False
146
+
147
+
148
+ def run(ctx: ExecutionContext) -> None:
149
+ require_root(ctx)
150
+ typer.echo("Instalando Kong Gateway via Helm...")
151
+
152
+ # Prompt opcional de limpeza
153
+ if _check_existing_kong(ctx):
154
+ cleanup = typer.confirm(
155
+ "Instalacao anterior do Kong detectada. Limpar antes de reinstalar?",
156
+ default=False,
157
+ )
158
+ if cleanup:
159
+ _uninstall_kong(ctx)
160
+
161
+ # Verificar CRDs orfaos (sem ownership do Helm)
162
+ orphan_crds = _check_orphan_crds(ctx)
163
+ if orphan_crds:
164
+ typer.secho(
165
+ f"\n⚠️ Detectados {len(orphan_crds)} CRDs orfaos do Kong (sem ownership do Helm):",
166
+ fg=typer.colors.YELLOW,
167
+ )
168
+ for crd in orphan_crds[:5]:
169
+ typer.echo(f" - {crd}")
170
+ if len(orphan_crds) > 5:
171
+ typer.echo(f" ... e mais {len(orphan_crds) - 5}")
172
+
173
+ cleanup_crds = typer.confirm(
174
+ "\nRemover CRDs orfaos para permitir instalacao limpa?",
175
+ default=True,
176
+ )
177
+ if cleanup_crds:
178
+ _cleanup_orphan_crds(ctx, orphan_crds)
179
+ else:
180
+ typer.secho(
181
+ "AVISO: A instalacao pode falhar devido aos CRDs orfaos.",
182
+ fg=typer.colors.YELLOW,
183
+ )
184
+
185
+ # Detectar dependencias
186
+ has_metallb = _check_metallb_installed(ctx)
187
+ has_cert_manager = _check_cert_manager_installed(ctx)
188
+
189
+ # Tipo de servico baseado na presenca do MetalLB
190
+ if has_metallb:
191
+ typer.secho("✓ MetalLB detectado. Kong usará LoadBalancer.", fg=typer.colors.GREEN)
192
+ service_type = "LoadBalancer"
193
+ else:
194
+ typer.secho("⚠ MetalLB não detectado. Kong usará NodePort.", fg=typer.colors.YELLOW)
195
+ service_type = "NodePort"
196
+
197
+ if has_cert_manager:
198
+ typer.secho("✓ cert-manager detectado. TLS automático disponível.", fg=typer.colors.GREEN)
199
+ else:
200
+ typer.secho("⚠ cert-manager não detectado. Configure TLS manualmente.", fg=typer.colors.YELLOW)
201
+
202
+ # Configuracoes interativas
203
+ enable_admin = typer.confirm("Habilitar Admin API (para gerenciamento)?", default=True)
204
+ enable_metrics = typer.confirm("Habilitar métricas Prometheus?", default=True)
205
+ db_mode = typer.prompt(
206
+ "Modo de banco de dados (dbless/postgres)",
207
+ default="dbless",
208
+ )
209
+
210
+ node_name = _detect_node_name(ctx)
211
+
212
+ # Usar arquivo YAML para configurações complexas (mais confiável que --set)
213
+ values_yaml = f"""env:
214
+ database: {db_mode}
215
+
216
+ ingressController:
217
+ installCRDs: true
218
+ enabled: true
219
+
220
+ proxy:
221
+ enabled: true
222
+ type: {service_type}
223
+ http:
224
+ enabled: true
225
+ containerPort: 8000
226
+ servicePort: 80
227
+ tls:
228
+ enabled: true
229
+ containerPort: 8443
230
+ servicePort: 443
231
+
232
+ admin:
233
+ enabled: {str(enable_admin).lower()}
234
+ type: ClusterIP
235
+ http:
236
+ enabled: true
237
+
238
+ tolerations:
239
+ - key: node-role.kubernetes.io/control-plane
240
+ operator: Exists
241
+ effect: NoSchedule
242
+ - key: node-role.kubernetes.io/master
243
+ operator: Exists
244
+ effect: NoSchedule
245
+
246
+ nodeSelector:
247
+ kubernetes.io/hostname: {node_name}
248
+
249
+ resources:
250
+ requests:
251
+ memory: 256Mi
252
+ cpu: 100m
253
+ limits:
254
+ memory: 1Gi
255
+ """
256
+
257
+ # Adicionar métricas se habilitado
258
+ if enable_metrics:
259
+ values_yaml += """
260
+ serviceMonitor:
261
+ enabled: true
262
+ namespace: kong
263
+ labels:
264
+ release: kube-prometheus-stack
265
+
266
+ podAnnotations:
267
+ prometheus.io/scrape: "true"
268
+ prometheus.io/port: "8100"
269
+ """
270
+
271
+ values_path = Path("/tmp/raijin-kong-values.yaml")
272
+ write_file(values_path, values_yaml, ctx)
273
+
274
+ run_cmd(["kubectl", "create", "namespace", "kong"], ctx, check=False)
275
+
276
+ helm_upgrade_install(
277
+ release="kong",
278
+ chart="kong",
279
+ namespace="kong",
280
+ repo="kong",
281
+ repo_url="https://charts.konghq.com",
282
+ ctx=ctx,
283
+ values=[],
284
+ extra_args=["-f", str(values_path)],
285
+ )
286
+
287
+ # Aguarda pods ficarem prontos
288
+ if not ctx.dry_run:
289
+ _wait_for_kong_ready(ctx)
290
+
291
+ # Mostra informacoes uteis
292
+ typer.secho("\n✓ Kong Gateway instalado com sucesso.", fg=typer.colors.GREEN, bold=True)
293
+
294
+ typer.echo("\n📌 Acesso ao Kong Proxy:")
295
+ if service_type == "LoadBalancer":
296
+ typer.echo(" kubectl -n kong get svc kong-kong-proxy # Aguarde EXTERNAL-IP")
297
+ else:
298
+ typer.echo(" kubectl -n kong get svc kong-kong-proxy # Use NodePort")
299
+
300
+ if enable_admin:
301
+ typer.echo("\n📌 Admin API (port-forward):")
302
+ typer.echo(" kubectl -n kong port-forward svc/kong-kong-admin 8001:8001")
303
+ typer.echo(" curl http://localhost:8001/status")
304
+
305
+ if enable_metrics:
306
+ typer.echo("\n📌 Métricas Prometheus:")
307
+ typer.echo(" ServiceMonitor criado - métricas serão coletadas automaticamente")
308
+
309
+ if has_cert_manager:
310
+ typer.echo("\n📌 TLS com cert-manager (exemplo de Ingress):")
311
+ typer.echo(""" ---
312
+ apiVersion: networking.k8s.io/v1
313
+ kind: Ingress
314
+ metadata:
315
+ name: my-api
316
+ annotations:
317
+ cert-manager.io/cluster-issuer: letsencrypt-prod
318
+ konghq.com/strip-path: "true"
319
+ spec:
320
+ ingressClassName: kong
321
+ tls:
322
+ - hosts: [api.example.com]
323
+ secretName: api-tls
324
+ rules:
325
+ - host: api.example.com
326
+ http:
327
+ paths:
328
+ - path: /
329
+ pathType: Prefix
330
+ backend:
331
+ service:
332
+ name: my-service
333
+ port:
334
+ number: 80""")
@@ -269,7 +269,7 @@ scheduler: {{}}
269
269
  ---
270
270
  apiVersion: kubeproxy.config.k8s.io/v1alpha1
271
271
  kind: KubeProxyConfiguration
272
- mode: ipvs
272
+ mode: iptables
273
273
  ---
274
274
  apiVersion: kubelet.config.k8s.io/v1beta1
275
275
  kind: KubeletConfiguration
@@ -331,3 +331,34 @@ cgroupDriver: systemd
331
331
  "--all",
332
332
  "--timeout=180s",
333
333
  ], ctx, check=False)
334
+
335
+ # Em clusters single-node, perguntar se deve remover taint do control-plane
336
+ # para permitir que workloads rodem no mesmo node
337
+ typer.secho("\n📌 Configuração de Single-Node Cluster", fg=typer.colors.CYAN, bold=True)
338
+ typer.echo("Se este for um cluster single-node (apenas este servidor),")
339
+ typer.echo("é necessário remover o taint do control-plane para permitir workloads.")
340
+
341
+ remove_taint = typer.confirm(
342
+ "Remover taint do control-plane (necessário para single-node)?",
343
+ default=True,
344
+ )
345
+
346
+ if remove_taint:
347
+ typer.echo("Removendo taint node-role.kubernetes.io/control-plane...")
348
+ run_cmd(
349
+ ["kubectl", "taint", "nodes", "--all", "node-role.kubernetes.io/control-plane-", "--overwrite"],
350
+ ctx,
351
+ check=False,
352
+ )
353
+ typer.secho("✓ Taint removido. Workloads podem rodar neste node.", fg=typer.colors.GREEN)
354
+ else:
355
+ typer.secho(
356
+ "⚠ Taint mantido. Workloads precisarão de tolerations ou worker nodes.",
357
+ fg=typer.colors.YELLOW,
358
+ )
359
+
360
+ typer.secho("\n✓ Kubernetes instalado com sucesso!", fg=typer.colors.GREEN, bold=True)
361
+ typer.echo("\nPróximos passos:")
362
+ typer.echo(" raijin-server install metallb # LoadBalancer para bare-metal")
363
+ typer.echo(" raijin-server install traefik # Ingress Controller")
364
+ typer.echo(" raijin-server install cert-manager # Certificados TLS automáticos")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: raijin-server
3
- Version: 0.2.24
3
+ Version: 0.2.26
4
4
  Summary: CLI para automacao de setup e hardening de servidores Ubuntu Server.
5
5
  Home-page: https://example.com/raijin-server
6
6
  Author: Equipe Raijin
@@ -1,5 +0,0 @@
1
- """Pacote principal do CLI Raijin Server."""
2
-
3
- __version__ = "0.2.24"
4
-
5
- __all__ = ["__version__"]
@@ -1,163 +0,0 @@
1
- """Configuracao do Kong Gateway via Helm com configuracoes production-ready."""
2
-
3
- import socket
4
- import time
5
-
6
- import typer
7
-
8
- from raijin_server.utils import ExecutionContext, helm_upgrade_install, require_root, run_cmd
9
-
10
-
11
- def _detect_node_name(ctx: ExecutionContext) -> str:
12
- """Detecta nome do node para nodeSelector."""
13
- result = run_cmd(
14
- ["kubectl", "get", "nodes", "-o", "jsonpath={.items[0].metadata.name}"],
15
- ctx,
16
- check=False,
17
- )
18
- if result.returncode == 0 and (result.stdout or "").strip():
19
- return (result.stdout or "").strip()
20
- return socket.gethostname()
21
-
22
-
23
- def _check_existing_kong(ctx: ExecutionContext) -> bool:
24
- """Verifica se existe instalacao do Kong."""
25
- result = run_cmd(
26
- ["helm", "status", "kong", "-n", "kong"],
27
- ctx,
28
- check=False,
29
- )
30
- return result.returncode == 0
31
-
32
-
33
- def _uninstall_kong(ctx: ExecutionContext) -> None:
34
- """Remove instalacao anterior do Kong."""
35
- typer.echo("Removendo instalacao anterior do Kong...")
36
-
37
- run_cmd(
38
- ["helm", "uninstall", "kong", "-n", "kong"],
39
- ctx,
40
- check=False,
41
- )
42
-
43
- run_cmd(
44
- ["kubectl", "delete", "namespace", "kong", "--ignore-not-found"],
45
- ctx,
46
- check=False,
47
- )
48
-
49
- time.sleep(5)
50
-
51
-
52
- def _wait_for_kong_ready(ctx: ExecutionContext, timeout: int = 180) -> bool:
53
- """Aguarda pods do Kong ficarem Ready."""
54
- typer.echo("Aguardando pods do Kong ficarem Ready...")
55
- deadline = time.time() + timeout
56
-
57
- while time.time() < deadline:
58
- result = run_cmd(
59
- [
60
- "kubectl", "-n", "kong", "get", "pods",
61
- "-o", "jsonpath={range .items[*]}{.metadata.name}={.status.phase} {end}",
62
- ],
63
- ctx,
64
- check=False,
65
- )
66
-
67
- if result.returncode == 0:
68
- output = (result.stdout or "").strip()
69
- if output:
70
- pods = []
71
- for item in output.split():
72
- if "=" in item:
73
- parts = item.rsplit("=", 1)
74
- if len(parts) == 2:
75
- pods.append((parts[0], parts[1]))
76
-
77
- if pods and all(phase == "Running" for _, phase in pods):
78
- typer.secho(f" Todos os {len(pods)} pods Running.", fg=typer.colors.GREEN)
79
- return True
80
-
81
- pending = [name for name, phase in pods if phase != "Running"]
82
- if pending:
83
- typer.echo(f" Aguardando: {', '.join(pending[:3])}...")
84
-
85
- time.sleep(10)
86
-
87
- typer.secho(" Timeout aguardando pods do Kong.", fg=typer.colors.YELLOW)
88
- return False
89
-
90
-
91
- def run(ctx: ExecutionContext) -> None:
92
- require_root(ctx)
93
- typer.echo("Instalando Kong Gateway via Helm...")
94
-
95
- # Prompt opcional de limpeza
96
- if _check_existing_kong(ctx):
97
- cleanup = typer.confirm(
98
- "Instalacao anterior do Kong detectada. Limpar antes de reinstalar?",
99
- default=False,
100
- )
101
- if cleanup:
102
- _uninstall_kong(ctx)
103
-
104
- # Configuracoes interativas
105
- enable_admin = typer.confirm("Habilitar Admin API (para gerenciamento)?", default=True)
106
- db_mode = typer.prompt(
107
- "Modo de banco de dados (dbless/postgres)",
108
- default="dbless",
109
- )
110
-
111
- node_name = _detect_node_name(ctx)
112
-
113
- values = [
114
- # Modo de operacao
115
- f"env.database={db_mode}",
116
- # Ingress Controller
117
- "ingressController.installCRDs=true",
118
- "ingressController.enabled=true",
119
- # Proxy service
120
- "proxy.enabled=true",
121
- "proxy.type=LoadBalancer",
122
- # Tolerations para control-plane
123
- "tolerations[0].key=node-role.kubernetes.io/control-plane",
124
- "tolerations[0].operator=Exists",
125
- "tolerations[0].effect=NoSchedule",
126
- "tolerations[1].key=node-role.kubernetes.io/master",
127
- "tolerations[1].operator=Exists",
128
- "tolerations[1].effect=NoSchedule",
129
- # NodeSelector
130
- f"nodeSelector.kubernetes\\.io/hostname={node_name}",
131
- ]
132
-
133
- # Admin API
134
- if enable_admin:
135
- values.extend([
136
- "admin.enabled=true",
137
- "admin.type=ClusterIP",
138
- "admin.http.enabled=true",
139
- ])
140
- else:
141
- values.append("admin.enabled=false")
142
-
143
- helm_upgrade_install(
144
- release="kong",
145
- chart="kong",
146
- namespace="kong",
147
- repo="kong",
148
- repo_url="https://charts.konghq.com",
149
- ctx=ctx,
150
- values=values,
151
- )
152
-
153
- # Aguarda pods ficarem prontos
154
- if not ctx.dry_run:
155
- _wait_for_kong_ready(ctx)
156
-
157
- # Mostra informacoes uteis
158
- typer.secho("\n✓ Kong instalado com sucesso.", fg=typer.colors.GREEN, bold=True)
159
- typer.echo("\nPara verificar o servico:")
160
- typer.echo(" kubectl -n kong get svc kong-kong-proxy")
161
- if enable_admin:
162
- typer.echo("\nPara acessar Admin API (port-forward):")
163
- typer.echo(" kubectl -n kong port-forward svc/kong-kong-admin 8001:8001")
File without changes
File without changes