Migrate Loki to Debian and preserve readable log data through Jeannie
This commit is contained in:
parent
f13ea0f6d1
commit
c85d26e16f
|
|
@ -1608,6 +1608,11 @@ resource "helm_release" "loki" {
|
|||
wait = true
|
||||
depends_on = [null_resource.calico_ready, kubernetes_storage_class_v1.openebs_hostpath_retain]
|
||||
|
||||
postrender {
|
||||
binary_path = "${path.module}/../../scripts/monitoring-helm-postrender.py"
|
||||
args = [var.external_loki_enabled ? var.external_monitoring_host : "", "loki"]
|
||||
}
|
||||
|
||||
values = [
|
||||
yamlencode({
|
||||
deploymentMode = "SingleBinary"
|
||||
|
|
@ -1643,7 +1648,7 @@ resource "helm_release" "loki" {
|
|||
}
|
||||
}
|
||||
singleBinary = {
|
||||
replicas = 1
|
||||
replicas = var.external_loki_enabled ? 0 : 1
|
||||
affinity = {}
|
||||
persistence = {
|
||||
enabled = true
|
||||
|
|
|
|||
|
|
@ -452,3 +452,9 @@ variable "extra_helm_releases" {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
variable "external_loki_enabled" {
|
||||
description = "Run Loki on Debian while preserving its cluster Service and PVC."
|
||||
type = bool
|
||||
default = false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -150,6 +150,7 @@ services:
|
|||
monitoring:
|
||||
host: debian
|
||||
external: true
|
||||
external_loki: true
|
||||
install_dir: /data/homelab-monitoring
|
||||
service_cidr: 10.43.0.0/16
|
||||
gitea:
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
# Debian monitoring
|
||||
|
||||
Prometheus, Alertmanager and Grafana run in the `homelab-prometheus` Compose
|
||||
Prometheus, Alertmanager, Grafana and Loki run in the `homelab-prometheus` Compose
|
||||
project on Debian's local NVMe. The Prometheus Operator, kube-state-metrics,
|
||||
node exporters and ServiceMonitor/PrometheusRule resources remain in K3s.
|
||||
Loki and Tempo remain in the cluster.
|
||||
Promtail and Tempo remain in the cluster.
|
||||
|
||||
Run on Debian:
|
||||
|
||||
|
|
@ -14,8 +14,8 @@ Run on Debian:
|
|||
```
|
||||
|
||||
`migrate` verifies the pinned cluster, validates exported configuration using
|
||||
promtool/amtool, stops only the three backends using the existing Helm release,
|
||||
then copies their offline volumes. It preserves the original PVCs and stores
|
||||
promtool/amtool, stops the retained backends using their existing Helm releases,
|
||||
then copies their offline volumes. Loki uses its own staged configuration check. It preserves the original PVCs and stores
|
||||
compressed archives, PVC identities and original Helm values under
|
||||
`/data/homelab-monitoring/backup`. Grafana's existing SQLite database is copied
|
||||
using SQLite's backup API, preserving users, saved dashboards and Dex account
|
||||
|
|
@ -53,8 +53,7 @@ private installation directory. Docker memory caps are 1536 MiB for Prometheus,
|
|||
512 MiB for Grafana and 256 MiB for Alertmanager. Coordinate LLM benchmarks
|
||||
with the remaining Debian memory; moving monitoring does not reserve host RAM.
|
||||
|
||||
The migration does not repair the Orange Pi SSD or migrate Loki. A down Loki
|
||||
target remains a real failure, rather than being hidden by this move. Original
|
||||
The migration does not repair the Orange Pi SSD. Original
|
||||
PVCs and backups should be retained until recovery requirements are reviewed.
|
||||
|
||||
`./jeannie monitoring apply`, `migrate` and `refresh` automatically check and
|
||||
|
|
@ -80,3 +79,25 @@ email VM is skipped. Status and validation commands remain read-only.
|
|||
Reconciliation finishes only after Prometheus observes the expected jobs UP;
|
||||
exporter failures fail the monitoring run and are visible in the timer journal. It needs the existing managed email rules, OCI CLI
|
||||
credentials, SSH key and passwordless sudo; it does not recreate either host.
|
||||
|
||||
Loki uses the same `./jeannie monitoring apply` migration/repair path. Its
|
||||
existing PVC is retained, and readable files are archived before being restored
|
||||
under `/data/homelab-monitoring/data/loki`. The `backup/loki` directory contains
|
||||
the original Helm values, PVC identity, compressed source data, copy warnings
|
||||
and file/byte counts. Read failures are reported rather than represented as a
|
||||
complete backup. Original archives are never rewritten on a successful retry.
|
||||
|
||||
The existing filesystem schema, chunk/index/WAL directories and seven-day
|
||||
retention policy remain in use. Archives preserve older source files even if
|
||||
normal Loki retention later removes them from the active store. The Helm
|
||||
post-renderer keeps the `loki.monitoring.svc:3100` address and redirects HTTP
|
||||
and gRPC to Debian; Promtail continues collecting in K3s. Grafana retains its
|
||||
Loki datasource UID, with a local backend URL on Debian. Native Loki config
|
||||
validation precedes rollout; refresh synchronizes configuration and labeled
|
||||
ConfigMap ruler rules, restarting Loki when its configuration changes.
|
||||
|
||||
Loki runs on ports 13100/19095 with a 768 MiB memory cap and half a CPU.
|
||||
The pinned Loki image is extended only with a static BusyBox HTTP health probe.
|
||||
Migration verifies readiness, a labels query, and a push through the cluster
|
||||
Service followed by querying that exact log record on Debian. The normal
|
||||
refresh timer checks Loki readiness too. No additional public endpoint is added.
|
||||
|
|
|
|||
|
|
@ -66,3 +66,23 @@ services:
|
|||
- ./config/grafana:/etc/grafana:ro
|
||||
- ./data/grafana:/var/lib/grafana
|
||||
- ./data/grafana-search:/var/lib/grafana-search
|
||||
loki:
|
||||
image: homelab/loki:3.6.7
|
||||
build:
|
||||
context: .
|
||||
dockerfile: loki.Dockerfile
|
||||
container_name: homelab-loki
|
||||
network_mode: host
|
||||
restart: unless-stopped
|
||||
mem_limit: 768m
|
||||
cpus: 0.5
|
||||
command: [-config.file=/etc/loki/config.yaml, -target=all]
|
||||
healthcheck:
|
||||
test: [CMD, /usr/local/bin/busybox, wget, -q, -O, /dev/null, 'http://127.0.0.1:13100/ready']
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 120s
|
||||
volumes:
|
||||
- ./config/loki:/etc/loki:ro
|
||||
- ./data/loki:/var/loki
|
||||
|
|
|
|||
|
|
@ -0,0 +1,3 @@
|
|||
FROM busybox:1.37.0-musl AS healthcheck
|
||||
FROM grafana/loki:3.6.7
|
||||
COPY --from=healthcheck /bin/busybox /usr/local/bin/busybox
|
||||
|
|
@ -44,6 +44,7 @@ mapping = {
|
|||
"hosts.oci_edge.tailscale_ip": "LAB_EDGE_TAILSCALE_IP",
|
||||
"hosts.oci_edge.install_dir": "LAB_EDGE_INSTALL_DIR",
|
||||
"services.gitea.http_port": "LAB_GITEA_HTTP_PORT",
|
||||
"services.monitoring.external_loki": "LAB_MONITORING_EXTERNAL_LOKI",
|
||||
"services.monitoring.external": "LAB_MONITORING_EXTERNAL",
|
||||
"services.monitoring.install_dir": "LAB_MONITORING_INSTALL_DIR",
|
||||
"services.monitoring.service_cidr": "LAB_MONITORING_SERVICE_CIDR",
|
||||
|
|
@ -328,6 +329,7 @@ export_homelab_inventory_tf_vars() {
|
|||
export_if_unset TF_VAR_oidc_backend_host "${LAB_DEX_BACKEND_HOST:-${LAB_DEBIAN_TAILSCALE_IP:-}}"
|
||||
export_if_unset TF_VAR_oidc_backend_port "${LAB_DEX_HTTP_PORT:-}"
|
||||
export_if_unset TF_VAR_grafana_oidc_url "${LAB_DEX_PUBLIC_URL:-}"
|
||||
export_if_unset TF_VAR_external_loki_enabled "${LAB_MONITORING_EXTERNAL_LOKI:-false}"
|
||||
export_if_unset TF_VAR_external_monitoring_enabled "${LAB_MONITORING_EXTERNAL:-false}"
|
||||
export_if_unset TF_VAR_external_monitoring_host "${LAB_DEBIAN_LAN_IP:-}"
|
||||
case "${LAB_MONITORING_EXTERNAL:-false}" in
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ monitoring_debian() {
|
|||
case "${action}" in
|
||||
exporters) monitoring_exporters; return $? ;;
|
||||
plan)
|
||||
echo "Move Prometheus, Alertmanager and Grafana to ${root} on Debian; preserve PVCs, database, dashboards and Dex."
|
||||
echo "Move Prometheus, Alertmanager, Grafana and enabled Loki to ${root} on Debian; preserve PVCs, database, dashboards and Dex."
|
||||
echo "Keep the Operator and exporters in K3s; refresh rules, discovery credentials and dashboards every five minutes."
|
||||
return 0 ;;
|
||||
status|validate)
|
||||
|
|
@ -64,10 +64,13 @@ monitoring_debian() {
|
|||
cluster_context_require || return 1
|
||||
record_change_journal "monitoring-${action}" "$@"
|
||||
sudo -n install -d -m 750 -o "$(id -un)" -g "$(id -gn)" "${root}" || return 1
|
||||
install -m 644 "${REPO_ROOT}/scripts/monitoring-loki.py" "${root}/monitoring-loki.py" || return 1
|
||||
install -m 755 "${REPO_ROOT}/scripts/monitoring-debian.py" "${root}/manager.py" || return 1
|
||||
install -m 755 "${REPO_ROOT}/scripts/monitoring-helm-postrender.py" "${root}/postrender.py" || return 1
|
||||
install -m 640 "${REPO_ROOT}/infra/monitoring-debian/compose.yaml" "${root}/compose.yaml" || return 1
|
||||
install -m 644 "${REPO_ROOT}/infra/monitoring-debian/loki.Dockerfile" "${root}/loki.Dockerfile" || return 1
|
||||
monitoring_exporter_install "${root}" || return 1
|
||||
LAB_MONITORING_EXTERNAL_LOKI="${LAB_MONITORING_EXTERNAL_LOKI:-false}" \
|
||||
MONITORING_ROOT="${root}" LAB_DEBIAN_LAN_IP="${LAB_DEBIAN_LAN_IP}" \
|
||||
LAB_PIMOX_HOST="${LAB_PIMOX_HOST}" LAB_PIMOX_USER="${LAB_PIMOX_USER}" \
|
||||
LAB_MONITORING_SERVICE_CIDR="${LAB_MONITORING_SERVICE_CIDR:-10.43.0.0/16}" python3 - <<'PY' || return 1
|
||||
|
|
@ -94,6 +97,9 @@ if not (root / 'settings.json').exists():
|
|||
networks=networks + [service_cidr], user=os.environ['USER'], home=os.environ['HOME'])
|
||||
(root / 'settings.json').write_text(json.dumps(settings, indent=2))
|
||||
(root / 'settings.json').chmod(0o600)
|
||||
settings = json.loads((root / 'settings.json').read_text())
|
||||
settings['loki_enabled'] = os.environ['LAB_MONITORING_EXTERNAL_LOKI'].lower() in ('true', '1', 'yes')
|
||||
(root / 'settings.json').write_text(json.dumps(settings, indent=2))
|
||||
PY
|
||||
python3 "${root}/manager.py" "${action}" --root "${root}" || return 1
|
||||
if [[ "${action}" == migrate ]]; then
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ def write(path, content, mode=0o640):
|
|||
temporary.replace(path)
|
||||
|
||||
|
||||
def external_config(config, api, services=None):
|
||||
def external_config(config, api, services=None, local_loki=False):
|
||||
"""Retain Operator discovery/relabeling and rules; use external API auth."""
|
||||
rendered = json.dumps(config).replace('$(SHARD)', '0').replace('$(POD_NAME)', 'debian-prometheus').replace('$(POD_NAMESPACE)', 'monitoring')
|
||||
if re.search(r'\$\([A-Z_]+\)', rendered):
|
||||
|
|
@ -55,7 +55,7 @@ def external_config(config, api, services=None):
|
|||
config = json.loads(rendered)
|
||||
for job in config.get('scrape_configs', []):
|
||||
for group in job.get('static_configs', []):
|
||||
group['targets'] = [service_url('http://' + target, services or {}).removeprefix('http://')
|
||||
group['targets'] = [service_url('http://' + target, services or {}, local_loki).removeprefix('http://')
|
||||
for target in group.get('targets', [])]
|
||||
for sd in job.get('kubernetes_sd_configs', []):
|
||||
sd.update(api_server=api, authorization={'credentials_file': '/var/run/secrets/kubernetes.io/serviceaccount/token'},
|
||||
|
|
@ -65,13 +65,15 @@ def external_config(config, api, services=None):
|
|||
return config
|
||||
|
||||
|
||||
def service_url(url, services):
|
||||
def service_url(url, services, local_loki=False):
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
host = parsed.hostname or ''
|
||||
bits = host.split('.')
|
||||
if len(bits) >= 2 and (bits[0], bits[1]) in services:
|
||||
name, namespace = bits[:2]
|
||||
if name in PORTS:
|
||||
if name == 'loki' and local_loki:
|
||||
address, port = '127.0.0.1', 13100
|
||||
elif name in PORTS:
|
||||
address, port = '127.0.0.1', PORTS[name]
|
||||
else:
|
||||
address, port = services[(name, namespace)], parsed.port
|
||||
|
|
@ -118,6 +120,13 @@ class Monitoring:
|
|||
for network in self.settings['networks']:
|
||||
run(['sudo', '-n', 'ip', 'route', 'replace', network, 'via', self.settings['node_ip']])
|
||||
|
||||
def loki(self):
|
||||
import importlib.util
|
||||
spec = importlib.util.spec_from_file_location('monitoring_loki', Path(__file__).with_name('monitoring-loki.py'))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module.Loki(self)
|
||||
|
||||
def refresh(self, reload=True):
|
||||
protected = [self.root / 'config/prometheus', self.root / 'config/alertmanager']
|
||||
previous = {path: path.read_bytes() for directory in protected for path in directory.rglob('*') if path.is_file()}
|
||||
|
|
@ -132,6 +141,9 @@ class Monitoring:
|
|||
write(path, content, 0o644)
|
||||
raise
|
||||
if reload:
|
||||
if self.settings.get('loki_enabled'):
|
||||
self.loki().refresh()
|
||||
self.wait_for(self.loki().validate)
|
||||
self.reconcile_exporters()
|
||||
|
||||
def reconcile_exporters(self):
|
||||
|
|
@ -146,7 +158,7 @@ class Monitoring:
|
|||
services = {(s['metadata']['name'], s['metadata']['namespace']): s['spec'].get('clusterIP')
|
||||
for s in self.get('services', namespace='*')['items']}
|
||||
config = yaml.safe_load(gzip.decompress(base64.b64decode(config_secret['data']['prometheus.yaml.gz'])))
|
||||
config = external_config(config, self.settings['api'], services)
|
||||
config = external_config(config, self.settings['api'], services, self.settings.get('loki_enabled', False))
|
||||
token = run(self.k + ['-n', 'monitoring', 'create', 'token', PROM, '--duration=1h']).strip()
|
||||
write(root / 'k8s/token', token, 0o644)
|
||||
write(root / 'k8s/ca.crt', base64.b64decode(self.settings['ca']), 0o644)
|
||||
|
|
@ -179,7 +191,7 @@ class Monitoring:
|
|||
document = yaml.safe_load(value)
|
||||
for ds in document.get('datasources', []):
|
||||
if isinstance(ds.get('url'), str):
|
||||
ds['url'] = service_url(ds['url'], services)
|
||||
ds['url'] = service_url(ds['url'], services, self.settings.get('loki_enabled', False))
|
||||
datasource_count += 1
|
||||
datasource_documents.append(document)
|
||||
destination = root / 'grafana/provisioning/datasources' / (cm['metadata']['name'] + '-' + Path(filename).name)
|
||||
|
|
@ -312,6 +324,8 @@ class Monitoring:
|
|||
|
||||
def migrate(self):
|
||||
self.verify_identity()
|
||||
if self.settings.get('loki_enabled'):
|
||||
self.loki().migrate()
|
||||
run(['sudo', '-n', 'install', '-d', '-m', '750', '-o', '472', '-g', '472', self.root / 'data/grafana-search'])
|
||||
if (self.root / 'migration-complete.json').exists():
|
||||
self.compose('up', '-d')
|
||||
|
|
@ -328,7 +342,7 @@ class Monitoring:
|
|||
write(backup / 'volumes.json', json.dumps(volumes, indent=2))
|
||||
if not (backup / 'helm-values.yaml').exists():
|
||||
write(backup / 'helm-values.yaml', run(['helm', '--kubeconfig', self.settings['kubeconfig'], '-n', 'monitoring', 'get', 'values', 'prometheus-stack', '-o', 'yaml']))
|
||||
self.compose('pull')
|
||||
self.compose('pull', '--ignore-buildable')
|
||||
self.refresh(reload=False)
|
||||
print('Configuration validated. Stopping only the three in-cluster monitoring backends.', flush=True)
|
||||
self.helm_external()
|
||||
|
|
@ -405,6 +419,8 @@ class Monitoring:
|
|||
run(['sudo', '-n', 'systemctl', 'enable', '--now', 'homelab-monitoring-refresh.timer'])
|
||||
|
||||
def http_ready(self):
|
||||
if self.settings.get('loki_enabled'):
|
||||
self.loki().validate()
|
||||
for name, port, path in (('prometheus', 19090, '/-/ready'), ('alertmanager', 19093, '/-/ready'), ('grafana', 13000, '/api/health')):
|
||||
self.http(f'http://127.0.0.1:{port}{path}')
|
||||
|
||||
|
|
|
|||
|
|
@ -5,25 +5,34 @@ import sys
|
|||
import yaml
|
||||
|
||||
|
||||
def render(documents, host):
|
||||
def render(documents, host, loki=False):
|
||||
ipaddress.IPv4Address(host)
|
||||
ports = {'prometheus-stack-grafana': 13000,
|
||||
'prometheus-stack-kube-prom-prometheus': 19090,
|
||||
'prometheus-stack-kube-prom-alertmanager': 19093}
|
||||
if loki:
|
||||
ports['loki'] = 13100
|
||||
output = []
|
||||
for item in documents:
|
||||
if not item:
|
||||
continue
|
||||
name = item.get('metadata', {}).get('name')
|
||||
if loki and item.get('kind') == 'StatefulSet' and name == 'loki':
|
||||
# The chart's default template can turn a zero value back into one.
|
||||
item['spec']['replicas'] = 0
|
||||
if item.get('kind') == 'Service' and name in ports:
|
||||
item['spec'].pop('selector', None)
|
||||
web = next(p for p in item['spec']['ports'] if p['name'] in ('http-web', 'http-web-svc'))
|
||||
web = next(p for p in item['spec']['ports'] if p['name'] in ('http-web', 'http-web-svc', 'http-metrics'))
|
||||
web['targetPort'] = ports[name]
|
||||
item['spec']['ports'] = [web]
|
||||
output.append({'apiVersion': 'v1', 'kind': 'Endpoints',
|
||||
'metadata': {'name': name, 'namespace': item['metadata']['namespace']},
|
||||
'subsets': [{'addresses': [{'ip': host}],
|
||||
'ports': [{'name': web['name'], 'port': ports[name], 'protocol': 'TCP'}]}]})
|
||||
if name == 'loki':
|
||||
grpc = {'name': 'grpc', 'port': 9095, 'targetPort': 19095, 'protocol': 'TCP'}
|
||||
item['spec']['ports'].append(grpc)
|
||||
output[-1]['subsets'][0]['ports'].append({'name': 'grpc', 'port': 19095, 'protocol': 'TCP'})
|
||||
output.append(item)
|
||||
return output
|
||||
|
||||
|
|
@ -33,4 +42,4 @@ if __name__ == '__main__':
|
|||
if len(sys.argv) < 2 or not sys.argv[1]:
|
||||
sys.stdout.write(raw)
|
||||
else:
|
||||
yaml.safe_dump_all(render(yaml.safe_load_all(raw), sys.argv[1]), sys.stdout, sort_keys=False)
|
||||
yaml.safe_dump_all(render(yaml.safe_load_all(raw), sys.argv[1], loki='loki' in sys.argv[2:]), sys.stdout, sort_keys=False)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,181 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Preserve readable Loki data and move the single-binary backend to Debian."""
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import tarfile
|
||||
import time
|
||||
import urllib.parse
|
||||
import yaml
|
||||
|
||||
|
||||
def run(args, **kwargs):
|
||||
result = subprocess.run([str(a) for a in args], capture_output=True, **kwargs)
|
||||
if result.returncode:
|
||||
raise RuntimeError(Path(str(args[0])).name + ' failed: ' + result.stderr.decode(errors='replace')[-1800:])
|
||||
return result.stdout
|
||||
|
||||
|
||||
def standalone(config):
|
||||
config = copy.deepcopy(config)
|
||||
config['server'].update(http_listen_port=13100, grpc_listen_port=19095)
|
||||
common = config.setdefault('common', {})
|
||||
common.update(instance_addr='127.0.0.1', compactor_grpc_address='127.0.0.1:19095',
|
||||
ring={'kvstore': {'store': 'inmemory'}})
|
||||
config.pop('memberlist', None)
|
||||
config['runtime_config'] = {'file': '/etc/loki/runtime-config.yaml'}
|
||||
# Preserve schema, paths and retention; a single local process needs no cluster DNS.
|
||||
return config
|
||||
|
||||
|
||||
class Loki:
|
||||
def __init__(self, monitoring):
|
||||
self.m = monitoring
|
||||
self.root = monitoring.root
|
||||
self.marker = self.root / 'loki-migration-complete.json'
|
||||
|
||||
def config(self):
|
||||
return standalone(yaml.safe_load(self.m.get('configmap', 'loki')['data']['config.yaml']))
|
||||
|
||||
def refresh(self, reload=True):
|
||||
directory = self.root / 'config/loki'
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
directory.chmod(0o755)
|
||||
document = yaml.safe_dump(self.config())
|
||||
runtime = self.m.get('configmap', 'loki-runtime').get('data', {}).get('runtime-config.yaml', '{}')
|
||||
rules = {}
|
||||
for cm in self.m.get('configmaps', namespace='*', labels='loki_rule')['items']:
|
||||
for filename, content in cm.get('data', {}).items():
|
||||
rules[cm['metadata']['namespace'] + '-' + cm['metadata']['name'] + '-' + Path(filename).name] = content
|
||||
fingerprint = hashlib.sha256((document + runtime + json.dumps(rules, sort_keys=True)).encode()).hexdigest()
|
||||
stamp = directory / 'fingerprint'
|
||||
old = stamp.read_text() if stamp.exists() else ''
|
||||
# Validate a staged config before publishing it to the running service.
|
||||
staged = directory / 'candidate.yaml'
|
||||
staged.write_text(document); staged.chmod(0o644)
|
||||
(directory / 'runtime-config.yaml').write_text(runtime)
|
||||
(directory / 'runtime-config.yaml').chmod(0o644)
|
||||
self.m.compose('run', '--rm', '--no-deps', 'loki', '-config.file=/etc/loki/candidate.yaml', '-verify-config=true')
|
||||
os.replace(staged, directory / 'config.yaml')
|
||||
destination = self.root / 'data/loki/rules/fake'
|
||||
run(['sudo', '-n', 'mkdir', '-p', destination])
|
||||
# Persist sidecar-provided ruler configuration without changing historical log files.
|
||||
for filename, content in rules.items():
|
||||
temporary = directory / filename
|
||||
temporary.write_text(content)
|
||||
run(['sudo', '-n', 'install', '-m', '644', '-o', '10001', '-g', '10001', temporary, destination / filename])
|
||||
temporary.unlink()
|
||||
if reload and fingerprint != old:
|
||||
self.m.compose('restart', 'loki')
|
||||
stamp.write_text(fingerprint)
|
||||
|
||||
def migrate(self):
|
||||
self.m.compose('build', 'loki')
|
||||
if self.marker.exists():
|
||||
self.refresh(reload=True)
|
||||
self.m.compose('up', '-d', 'loki')
|
||||
self.m.wait_for(self.validate)
|
||||
self.verify_ingestion()
|
||||
return
|
||||
pvc = self.m.get('pvc', 'storage-loki-0')
|
||||
pv = self.m.get('pv', pvc['spec']['volumeName'], namespace=None)
|
||||
ref = pv['spec']['claimRef']
|
||||
path = pv['spec'].get('local', {}).get('path', '')
|
||||
if ref['uid'] != pvc['metadata']['uid'] or ref['namespace'] != 'monitoring' or not path.startswith('/data/') or '..' in path.split('/'):
|
||||
raise RuntimeError('Loki PVC identity or retained local path is invalid')
|
||||
backup = self.root / 'backup/loki'
|
||||
backup.mkdir(parents=True, exist_ok=True)
|
||||
identity = {'pvc': pvc['metadata']['name'], 'uid': pvc['metadata']['uid'], 'pv': pv['metadata']['name'], 'path': path}
|
||||
(backup / 'volume.json').write_text(json.dumps(identity, indent=2))
|
||||
original = backup / 'helm-values.yaml'
|
||||
helm = ['helm', '--kubeconfig', self.m.settings['kubeconfig'], '-n', 'monitoring']
|
||||
if not original.exists():
|
||||
original.write_bytes(run(helm + ['get', 'values', 'loki', '-o', 'yaml']))
|
||||
self.refresh(reload=False)
|
||||
release = json.loads(run(helm + ['list', '--filter', '^loki$', '-o', 'json']))[0]
|
||||
version = release['chart'].removeprefix('loki-')
|
||||
service = self.m.get('service', 'loki')
|
||||
if service['metadata'].get('annotations', {}).get('meta.helm.sh/release-name') != 'loki':
|
||||
raise RuntimeError('Loki Service is not owned by the expected Helm release')
|
||||
existing = run(self.m.k + ['-n', 'monitoring', 'get', 'endpoints', 'loki', '--ignore-not-found', '-o', 'json'])
|
||||
if existing.strip():
|
||||
run(self.m.k + ['-n', 'monitoring', 'annotate', 'endpoints', 'loki', 'meta.helm.sh/release-name=loki', 'meta.helm.sh/release-namespace=monitoring', '--overwrite'])
|
||||
run(self.m.k + ['-n', 'monitoring', 'label', 'endpoints', 'loki', 'app.kubernetes.io/managed-by=Helm', '--overwrite'])
|
||||
renderer = str(self.root / 'postrender.py')
|
||||
environment = os.environ.copy()
|
||||
if run(['helm', 'version', '--short']).decode().startswith('v4.'):
|
||||
plugin = self.root / 'helm-plugins/jeannie-monitoring'
|
||||
plugin.mkdir(parents=True, exist_ok=True)
|
||||
(plugin / 'plugin.yaml').write_text(yaml.safe_dump({'apiVersion': 'v1', 'type': 'postrenderer/v1',
|
||||
'name': 'jeannie-monitoring', 'version': '1.0.0', 'runtime': 'subprocess',
|
||||
'runtimeConfig': {'platformCommand': [{'command': renderer}]}}))
|
||||
environment['HELM_PLUGINS'] = str(plugin.parent)
|
||||
renderer = 'jeannie-monitoring'
|
||||
values = self.root / 'loki-external-values.yaml'
|
||||
values.write_text('singleBinary:\n replicas: 0\n')
|
||||
run(helm + ['upgrade', 'loki', 'loki', '--repo', 'https://grafana.github.io/helm-charts', '--version', version,
|
||||
'--reuse-values', '-f', values, '--post-renderer', renderer,
|
||||
'--post-renderer-args', self.m.settings['debian_ip'], '--post-renderer-args', 'loki', '--timeout', '5m'], env=environment)
|
||||
deadline = time.monotonic() + 180
|
||||
while self.m.get('pods', labels='app.kubernetes.io/name=loki')['items']:
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError('Loki pods did not stop; refusing a live data copy')
|
||||
time.sleep(3)
|
||||
archive = backup / 'readable-data.tar.gz'
|
||||
if not archive.exists():
|
||||
command = 'findmnt -rn -M /data -o OPTIONS | grep -q "^rw" && sudo -n tar --ignore-failed-read -C ' + shlex.quote(path) + ' -czf - .'
|
||||
with archive.with_suffix('.partial').open('wb') as output:
|
||||
copied = subprocess.run(['ssh', '-T', self.m.settings['node_ssh'], command], stdout=output, stderr=subprocess.PIPE)
|
||||
(backup / 'copy-warnings.log').write_bytes(copied.stderr)
|
||||
if copied.returncode not in (0, 1):
|
||||
raise RuntimeError('Loki backup failed; partial archive and copy warnings retained')
|
||||
archive.with_suffix('.partial').replace(archive)
|
||||
destination = self.root / 'data/loki'
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
if not (backup / 'copied').exists():
|
||||
run(['sudo', '-n', 'chown', '-R', f'{os.getuid()}:{os.getgid()}', destination])
|
||||
with tarfile.open(archive) as source:
|
||||
members = source.getmembers()
|
||||
source.extractall(destination, filter='data')
|
||||
report = dict(identity, archived_files=sum(m.isfile() for m in members),
|
||||
archived_bytes=sum(m.size for m in members if m.isfile()),
|
||||
warnings=(backup / 'copy-warnings.log').read_text(errors='replace'))
|
||||
(backup / 'copy-report.json').write_text(json.dumps(report, indent=2))
|
||||
(backup / 'copied').write_text('copied\n')
|
||||
run(['sudo', '-n', 'chown', '-R', '10001:10001', destination])
|
||||
self.m.compose('up', '-d', 'loki')
|
||||
self.m.wait_for(self.validate)
|
||||
self.verify_ingestion()
|
||||
self.marker.write_text(json.dumps(identity, indent=2))
|
||||
print('Loki moved to Debian; original PVC and readable-data archive retained.')
|
||||
|
||||
def verify_ingestion(self):
|
||||
timestamp = time.time_ns()
|
||||
token = 'jeannie-' + str(timestamp)
|
||||
payload = json.dumps({'streams': [{'stream': {'job': 'jeannie-loki-check'},
|
||||
'values': [[str(timestamp), token]]}]}).encode()
|
||||
service = self.m.get('service', 'loki')['spec']
|
||||
command = ('curl -fsS --max-time 15 -H \'Content-Type: application/json\' --data-binary @- http://' +
|
||||
service['clusterIP'] + ':3100/loki/api/v1/push')
|
||||
run(['ssh', '-T', self.m.settings['node_ssh'], command], input=payload)
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
query = urllib.parse.urlencode({'query': '{job="jeannie-loki-check"}',
|
||||
'start': str(timestamp - 30_000_000_000), 'end': str(time.time_ns()), 'limit': '100'})
|
||||
response = json.loads(self.m.http('http://127.0.0.1:13100/loki/api/v1/query_range?' + query))
|
||||
if any(value[1] == token for stream in response['data']['result'] for value in stream.get('values', [])):
|
||||
print('Loki: cluster Service push and Debian query round-trip verified')
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('Loki accepted push but the validation log could not be queried')
|
||||
time.sleep(2)
|
||||
|
||||
def validate(self):
|
||||
self.m.http('http://127.0.0.1:13100/ready')
|
||||
# An actual query tests the index/read path, not merely process readiness.
|
||||
self.m.http('http://127.0.0.1:13100/loki/api/v1/labels')
|
||||
print('Loki: ready; labels query succeeded')
|
||||
|
|
@ -129,6 +129,7 @@ validate_unit_tests() {
|
|||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_focus.py'
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_stale_pod_candidate.py'
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_exporter_access.py'
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_loki.py'
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_debian.py'
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_readiness.py'
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_k3s_storage.py'
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ class MonitoringMigrationTests(unittest.TestCase):
|
|||
with tempfile.TemporaryDirectory() as directory:
|
||||
manager = MANAGER.Monitoring.__new__(MANAGER.Monitoring)
|
||||
manager.root = Path(directory)
|
||||
manager.settings = {}
|
||||
with patch.object(manager, '_refresh'), patch.object(manager, 'reconcile_exporters') as check:
|
||||
manager.refresh(reload=False)
|
||||
check.assert_not_called()
|
||||
|
|
@ -34,6 +35,7 @@ class MonitoringMigrationTests(unittest.TestCase):
|
|||
with tempfile.TemporaryDirectory() as directory:
|
||||
manager = MANAGER.Monitoring.__new__(MANAGER.Monitoring)
|
||||
manager.root = Path(directory)
|
||||
manager.settings = {}
|
||||
with patch.object(manager, '_refresh'), \
|
||||
patch.object(manager, 'reconcile_exporters', side_effect=RuntimeError('exporter down')):
|
||||
with self.assertRaisesRegex(RuntimeError, 'exporter down'):
|
||||
|
|
@ -43,6 +45,7 @@ class MonitoringMigrationTests(unittest.TestCase):
|
|||
with tempfile.TemporaryDirectory() as directory:
|
||||
manager = MANAGER.Monitoring.__new__(MANAGER.Monitoring)
|
||||
manager.root = Path(directory)
|
||||
manager.settings = {}
|
||||
original = manager.root / 'config/prometheus/prometheus.yaml'
|
||||
original.parent.mkdir(parents=True)
|
||||
original.write_text('last valid configuration')
|
||||
|
|
|
|||
|
|
@ -0,0 +1,75 @@
|
|||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
from unittest.mock import Mock, patch
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def load(filename):
|
||||
spec = importlib.util.spec_from_file_location(filename, ROOT / 'scripts' / (filename + '.py'))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
LOKI = load('monitoring-loki')
|
||||
RENDER = load('monitoring-helm-postrender')
|
||||
MANAGER = load('monitoring-debian')
|
||||
|
||||
|
||||
class LokiMigrationTests(unittest.TestCase):
|
||||
def test_standalone_preserves_log_schema_storage_and_retention(self):
|
||||
original = {'server': {'http_listen_port': 3100, 'grpc_listen_port': 9095},
|
||||
'common': {'path_prefix': '/var/loki', 'storage': {'filesystem': {'chunks_directory': '/var/loki/chunks'}}},
|
||||
'schema_config': {'configs': [{'from': '2024-04-01', 'schema': 'v13', 'store': 'tsdb'}]},
|
||||
'limits_config': {'retention_period': '168h'}, 'memberlist': {'join_members': ['loki.cluster']}}
|
||||
before = copy.deepcopy(original)
|
||||
result = LOKI.standalone(original)
|
||||
for key in ('schema_config', 'limits_config'):
|
||||
self.assertEqual(result[key], original[key])
|
||||
self.assertEqual(result['common']['storage'], original['common']['storage'])
|
||||
self.assertNotIn('memberlist', result)
|
||||
self.assertEqual(result['common']['ring']['kvstore']['store'], 'inmemory')
|
||||
self.assertEqual(result['server']['http_listen_port'], 13100)
|
||||
self.assertEqual(original, before)
|
||||
|
||||
def test_loki_service_preserves_http_and_grpc_ports_and_names(self):
|
||||
service = {'kind': 'Service', 'metadata': {'name': 'loki', 'namespace': 'monitoring'},
|
||||
'spec': {'selector': {'app': 'loki'}, 'ports': [
|
||||
{'name': 'http-metrics', 'port': 3100, 'targetPort': 'http-metrics'},
|
||||
{'name': 'grpc', 'port': 9095, 'targetPort': 'grpc'}]}}
|
||||
endpoints, result = RENDER.render([service], '192.168.100.73', loki=True)
|
||||
self.assertNotIn('selector', result['spec'])
|
||||
self.assertEqual([p['port'] for p in result['spec']['ports']], [3100, 9095])
|
||||
self.assertEqual([p['port'] for p in endpoints['subsets'][0]['ports']], [13100, 19095])
|
||||
|
||||
def test_chart_default_cannot_restore_local_loki_replicas(self):
|
||||
sts = {'kind': 'StatefulSet', 'metadata': {'name': 'loki'}, 'spec': {'replicas': 1}}
|
||||
self.assertEqual(RENDER.render([sts], '192.168.100.73', loki=True)[0]['spec']['replicas'], 0)
|
||||
|
||||
def test_ingestion_probe_uses_cluster_service_then_reads_exact_record(self):
|
||||
monitoring = Mock()
|
||||
monitoring.root = Path('/test')
|
||||
monitoring.settings = {'node_ssh': 'node'}
|
||||
monitoring.get.return_value = {'spec': {'clusterIP': '10.43.1.2'}}
|
||||
monitoring.http.return_value = json.dumps({'data': {'result': [{'values': [['123', 'jeannie-123']]}]}}).encode()
|
||||
with patch.object(LOKI.time, 'time_ns', return_value=123), patch.object(LOKI, 'run') as execute:
|
||||
LOKI.Loki(monitoring).verify_ingestion()
|
||||
self.assertIn('http://10.43.1.2:3100/loki/api/v1/push', execute.call_args.args[0][-1])
|
||||
self.assertIn(b'jeannie-123', execute.call_args.kwargs['input'])
|
||||
self.assertIn('/loki/api/v1/query_range?', monitoring.http.call_args.args[0])
|
||||
|
||||
def test_cluster_loki_is_unchanged_when_external_mode_is_disabled(self):
|
||||
service = {'kind': 'Service', 'metadata': {'name': 'loki'}, 'spec': {'selector': {'app': 'loki'}}}
|
||||
self.assertEqual(RENDER.render([service], '192.168.100.73'), [service])
|
||||
url = 'http://loki.monitoring.svc:3100'
|
||||
services = {('loki', 'monitoring'): '10.43.1.2'}
|
||||
self.assertEqual(MANAGER.service_url(url, services), 'http://10.43.1.2:3100')
|
||||
self.assertEqual(MANAGER.service_url(url, services, local_loki=True), 'http://127.0.0.1:13100')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue