Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Generated index artifacts
vector_db/
embeddings_model/
.hf_cache/

# Python
__pycache__/
Expand Down
3 changes: 2 additions & 1 deletion Containerfile
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ RUN uv pip install --system --no-cache \
pyyaml \
tqdm

# Copy sources and config
# Copy sources, config, and curated YAML examples
COPY build_index.py config.yaml ./
COPY docs/ ./docs/

# Build a single merged index (Kiali + Istio sources combined)
RUN python build_index.py \
Expand Down
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ CONTAINER_TOOL ?= podman
CONFIG ?= config.yaml
VECTOR_DB_DIR ?= vector_db/kiali
EMBEDDING_MODEL ?= sentence-transformers/all-mpnet-base-v2
HF_HOME ?= $(CURDIR)/.hf_cache
export HF_HOME

VERSION := $(shell cat VERSION | tr -d '[:space:]')

Expand Down
103 changes: 91 additions & 12 deletions build_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,25 +172,104 @@ def load_documents_from_web(cfg: dict) -> list:
return documents


def _parse_frontmatter(text: str) -> tuple[dict, str]:
"""Parse optional YAML frontmatter from a markdown document."""
if not text.startswith("---"):
return {}, text

parts = text.split("---", 2)
if len(parts) < 3:
return {}, text

try:
frontmatter = yaml.safe_load(parts[1]) or {}
except yaml.YAMLError:
return {}, text

if not isinstance(frontmatter, dict):
return {}, text

body = parts[2].lstrip("\n")
return frontmatter, body


def _build_local_document_text(frontmatter: dict, body: str) -> str:
"""Prepend structured metadata so embeddings capture example context."""
header_lines: list[str] = []
if title := frontmatter.get("title"):
header_lines.append(f"# {title}")
if category := frontmatter.get("category"):
header_lines.append(f"Category: {category}")
if versions := frontmatter.get("istio_versions"):
if isinstance(versions, list):
header_lines.append(f"Istio versions: {', '.join(str(v) for v in versions)}")
else:
header_lines.append(f"Istio versions: {versions}")
if crds := frontmatter.get("crd_types"):
if isinstance(crds, list):
header_lines.append(f"CRDs: {', '.join(crds)}")
else:
header_lines.append(f"CRDs: {crds}")
if description := frontmatter.get("description"):
header_lines.append(description)

if not header_lines:
return body
return "\n\n".join(header_lines) + "\n\n" + body


def load_documents_from_local(cfg: dict) -> list:
"""Read markdown/text/HTML files from a local directory."""
from llama_index.core import SimpleDirectoryReader
from llama_index.core import Document

local_path = cfg.get("local_path", "./docs")
local_path = Path(cfg.get("local_path", "./docs"))
extensions = cfg.get("file_extensions", [".md", ".rst", ".txt", ".html"])
logger.info("Reading local files from %s (extensions: %s)", local_path, extensions)

reader = SimpleDirectoryReader(
input_dir=local_path,
required_exts=extensions,
recursive=True,
)
documents = reader.load_data()
if not local_path.exists():
logger.warning("Local path does not exist: %s", local_path)
return []

documents: list[Document] = []
for file_path in sorted(local_path.rglob("*")):
if not file_path.is_file() or file_path.suffix not in extensions:
continue

raw_text = file_path.read_text(encoding="utf-8")
frontmatter, body = _parse_frontmatter(raw_text)
text = _build_local_document_text(frontmatter, body)
if len(text.strip()) < 50:
logger.debug("Skipping short local file: %s", file_path)
continue

rel_path = file_path.relative_to(local_path)
title = frontmatter.get("title") or file_path.stem.replace("-", " ").title()
docs_url = frontmatter.get(
"docs_url",
f"file://{file_path.resolve()}",
)

metadata = {
"title": title,
"docs_url": docs_url,
"file_name": file_path.name,
"file_path": str(file_path.resolve()),
}
for key in ("category", "description"):
if key in frontmatter:
metadata[key] = frontmatter[key]
if versions := frontmatter.get("istio_versions"):
metadata["istio_versions"] = (
", ".join(str(v) for v in versions)
if isinstance(versions, list)
else str(versions)
)
if crds := frontmatter.get("crd_types"):
metadata["crd_types"] = (
", ".join(crds) if isinstance(crds, list) else str(crds)
)

# Ensure metadata fields expected by OLS are present
for doc in documents:
doc.metadata.setdefault("title", Path(doc.metadata.get("file_name", "unknown")).stem)
doc.metadata.setdefault("docs_url", doc.metadata.get("file_path", ""))
documents.append(Document(text=text, metadata=metadata))

logger.info("Loaded %d documents from local path", len(documents))
return documents
Expand Down
5 changes: 5 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ sources:
request_timeout: 30
crawl_delay: 0.1

# Curated, production-ready Istio YAML examples (committed in-repo)
- type: local
local_path: ./docs/istio-yaml-examples
file_extensions: [".md"]

# -------------------------------------------------------
# Embedding model
# -------------------------------------------------------
Expand Down
34 changes: 34 additions & 0 deletions docs/istio-yaml-examples/resilience/circuit-breaker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
title: "DestinationRule — Circuit Breaker"
category: resilience
description: "Trip the circuit when consecutive errors exceed a threshold to protect upstream services."
istio_versions: ["1.20", "1.21", "1.22", "1.23", "1.24"]
crd_types: ["DestinationRule"]
docs_url: "https://github.com/kiali/kiali-byok/blob/main/docs/istio-yaml-examples/resilience/circuit-breaker.md"
---

Circuit breaker: eject unhealthy hosts after 5 consecutive 5xx errors within 30 seconds.

```yaml
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
name: ratings-cb
namespace: bookinfo
spec:
host: ratings
trafficPolicy:
connectionPool:
tcp:
maxConnections: 100
http:
http1MaxPendingRequests: 50
maxRequestsPerConnection: 2
outlierDetection:
consecutive5xxErrors: 5 # trip after 5 consecutive 5xx
interval: 30s # evaluation window
baseEjectionTime: 30s # host ejected for at least 30s
maxEjectionPercent: 50 # max 50% of hosts ejected at once
```

Combine with connection pool limits to prevent retry storms during outages.
32 changes: 32 additions & 0 deletions docs/istio-yaml-examples/resilience/connection-pool.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
title: "DestinationRule — Connection Pool Settings"
category: resilience
description: "Limit concurrent connections and pending requests to prevent resource exhaustion."
istio_versions: ["1.20", "1.21", "1.22", "1.23", "1.24"]
crd_types: ["DestinationRule"]
docs_url: "https://github.com/kiali/kiali-byok/blob/main/docs/istio-yaml-examples/resilience/connection-pool.md"
---

Connection pool: cap TCP connections and HTTP pending requests to the reviews service.

```yaml
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
name: reviews-pool
namespace: bookinfo
spec:
host: reviews
trafficPolicy:
connectionPool:
tcp:
maxConnections: 50 # max TCP connections to each upstream host
connectTimeout: 30ms # fail fast on connect
http:
http2MaxRequests: 100 # max concurrent HTTP/2 requests
http1MaxPendingRequests: 50 # queue limit for HTTP/1.1
maxRequestsPerConnection: 10 # connection reuse limit
idleTimeout: 60s # close idle connections after 60s
```

Tune based on pod CPU/memory and upstream capacity. Monitor 503 URX (upstream reset) metrics.
31 changes: 31 additions & 0 deletions docs/istio-yaml-examples/resilience/outlier-detection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
title: "DestinationRule — Outlier Detection"
category: resilience
description: "Automatically eject unhealthy hosts from the load balancing pool."
istio_versions: ["1.20", "1.21", "1.22", "1.23", "1.24"]
crd_types: ["DestinationRule"]
docs_url: "https://github.com/kiali/kiali-byok/blob/main/docs/istio-yaml-examples/resilience/outlier-detection.md"
---

Outlier detection: remove pods returning errors or high latency from the rotation.

```yaml
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
name: ratings-outlier
namespace: bookinfo
spec:
host: ratings
trafficPolicy:
outlierDetection:
consecutive5xxErrors: 3 # eject after 3 consecutive 5xx
consecutiveGatewayErrors: 3
interval: 10s # scan interval
baseEjectionTime: 30s # minimum ejection duration
maxEjectionPercent: 30 # never eject more than 30% of endpoints
minHealthPercent: 50 # stop ejecting if <50% hosts remain healthy
splitExternalLocalOriginErrors: true
```

Works with Kubernetes readiness probes — outlier detection handles transient failures between probe intervals.
33 changes: 33 additions & 0 deletions docs/istio-yaml-examples/resilience/retry-exponential-backoff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
title: "VirtualService — Retry with Exponential Backoff"
category: resilience
description: "Retry failed requests with configurable attempts, timeout, and per-try timeout."
istio_versions: ["1.20", "1.21", "1.22", "1.23", "1.24"]
crd_types: ["VirtualService"]
docs_url: "https://github.com/kiali/kiali-byok/blob/main/docs/istio-yaml-examples/resilience/retry-exponential-backoff.md"
---

Retry policy: retry up to 3 times on gateway errors and connection failures.

```yaml
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
name: ratings-retry
namespace: bookinfo
spec:
hosts:
- ratings
http:
- route:
- destination:
host: ratings
timeout: 10s # total request budget
retries:
attempts: 3 # max retry attempts
perTryTimeout: 2s # timeout per individual try
retryOn: 5xx,reset,connect-failure,refused-stream
# Envoy applies exponential backoff between retries automatically
```

Idempotent methods (GET, HEAD) are safest for retries. Use caution with POST/PUT.
42 changes: 42 additions & 0 deletions docs/istio-yaml-examples/resilience/timeout-configuration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
title: "VirtualService — Request Timeout"
category: resilience
description: "Set per-route timeouts to prevent slow upstreams from blocking callers."
istio_versions: ["1.20", "1.21", "1.22", "1.23", "1.24"]
crd_types: ["VirtualService"]
docs_url: "https://github.com/kiali/kiali-byok/blob/main/docs/istio-yaml-examples/resilience/timeout-configuration.md"
---

Timeout: fail fast if `details` service does not respond within 3 seconds.

```yaml
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
name: details-timeout
namespace: bookinfo
spec:
hosts:
- details
http:
- route:
- destination:
host: details
timeout: 3s # return 504 if upstream exceeds 3s
```

Global default timeout in mesh config (IstioOperator):

```yaml
apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
metadata:
name: mesh-timeouts
spec:
meshConfig:
defaultConfig:
holdApplicationUntilProxyStarts: true
# Per-route VirtualService timeouts override mesh defaults
```

Always set timeouts shorter than client-side deadlines to surface errors cleanly.
40 changes: 40 additions & 0 deletions docs/istio-yaml-examples/security/authorization-policy-deny-all.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
title: "AuthorizationPolicy — Deny-All Default (Security Best Practice)"
category: security
description: "Start with a namespace-wide deny-all policy, then add explicit ALLOW rules."
istio_versions: ["1.20", "1.21", "1.22", "1.23", "1.24"]
crd_types: ["AuthorizationPolicy"]
docs_url: "https://github.com/kiali/kiali-byok/blob/main/docs/istio-yaml-examples/security/authorization-policy-deny-all.md"
---

Security best practice: zero-trust baseline — deny everything, then whitelist per service.

```yaml
# Namespace-wide deny-all (applies to all workloads in the namespace)
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
name: deny-all
namespace: production
spec:
{} # empty spec = deny all inbound traffic
---
# Explicit allow for health checks from the mesh
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
name: allow-health-checks
namespace: production
spec:
selector:
matchLabels:
app: my-service
action: ALLOW
rules:
- to:
- operation:
paths: ["/health", "/ready"]
methods: ["GET"]
```

Add one ALLOW policy per service pair as you onboard workloads.
Loading
Loading