All files / src/app/api/admin/components route.ts

69.4% Statements 93/134
47.56% Branches 39/82
77.77% Functions 14/18
69.76% Lines 90/129

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                  1x         1x           1x       48x 48x     34x 34x 34x 34x 34x             48x 48x       48x                       1x                                                                                                                                                                                                                                                                                               12x     12x 12x 12x 12x                   12x 12x 12x 12x                                                                                 1x                                                                                                                                                                                                           24x 24x 24x     24x       24x         24x       24x 24x 24x 24x       24x                 24x 24x 24x       10x   10x   200x 236x   200x 188x             188x       12x 12x 12x 12x     12x 11x     12x 12x 12x 12x 12x           12x 12x 12x 12x     12x 12x         12x         14x             14x 280x                       24x   24x         6x 6x 6x             6x 12x 12x 12x               12x   12x     12x   12x       12x                     18x           24x 18x 18x                             18x                                 24x 24x 1227x           24x           24x                  
import { getServerSession } from "next-auth/next";
import { NextResponse } from "next/server";
import http from "node:http";
import { edcClient } from "@/lib/edc";
import { runQuery } from "@/lib/neo4j";
import {
  azureResourceGroup,
  azureSubscriptionId,
  getContainerAppMetrics,
  isAzureDeployment,
  listContainerApps,
  parseMemoryToBytes,
} from "@/lib/azure-arm";
 
import { authOptions } from "@/lib/auth";
import { cached } from "@/lib/server-cache";
 
export const dynamic = "force-dynamic";
 
// First load on Azure spends 3-6s in ARM (list + per-app metrics) + ~1s in
// CFM/Neo4j; serving stale data for up to 30s makes navigation feel instant
// while keeping the dashboard fresh enough for live monitoring.
const CACHE_TTL_MS = 30_000;
 
// ---------------------------------------------------------------------------
// Docker Engine API helpers (via Unix socket)
// ---------------------------------------------------------------------------
 
const DOCKER_SOCKET = "/var/run/docker.sock";
 
/** Make a GET request to the Docker Engine API. */
function dockerGet<T>(path: string): Promise<T> {
  return new Promise((resolve, reject) => {
    const req = http.request(
      { socketPath: DOCKER_SOCKET, path, method: "GET" },
      (res) => {
        let data = "";
        res.on("data", (chunk: Buffer) => (data += chunk.toString()));
        res.on("end", () => {
          try {
            resolve(JSON.parse(data) as T);
          } catch {
            reject(new Error(`Docker API parse error: ${data.slice(0, 200)}`));
          }
        });
      },
    );
    req.on("error", reject);
    req.setTimeout(5000, () => {
      req.destroy();
      reject(new Error("Docker API timeout"));
    });
    req.end();
  });
}
 
// Map container names → participant and component role
interface ServiceMapping {
  container: string;
  component: string;
  layer: "edc-core" | "identity" | "cfm" | "infrastructure";
  participant?: string; // undefined = shared
}
 
const SERVICE_MAP: ServiceMapping[] = [
  {
    container: "health-dataspace-controlplane",
    component: "Control Plane",
    layer: "edc-core",
  },
  {
    container: "health-dataspace-dataplane-fhir",
    component: "Data Plane FHIR",
    layer: "edc-core",
  },
  {
    container: "health-dataspace-dataplane-omop",
    component: "Data Plane OMOP",
    layer: "edc-core",
  },
  {
    container: "health-dataspace-identityhub",
    component: "Identity Hub",
    layer: "identity",
  },
  {
    container: "health-dataspace-issuerservice",
    component: "Issuer Service",
    layer: "identity",
  },
  {
    container: "health-dataspace-keycloak",
    component: "Keycloak",
    layer: "identity",
  },
  {
    container: "health-dataspace-vault",
    component: "Vault",
    layer: "identity",
  },
  {
    container: "health-dataspace-vault-bootstrap",
    component: "Vault Bootstrap",
    layer: "identity",
  },
  {
    container: "health-dataspace-tenant-manager",
    component: "Tenant Manager",
    layer: "cfm",
  },
  {
    container: "health-dataspace-provision-manager",
    component: "Provision Manager",
    layer: "cfm",
  },
  {
    container: "health-dataspace-cfm-edcv-agent",
    component: "EDC-V Agent",
    layer: "cfm",
  },
  {
    container: "health-dataspace-cfm-keycloak-agent",
    component: "Keycloak Agent",
    layer: "cfm",
  },
  {
    container: "health-dataspace-cfm-onboarding-agent",
    component: "Onboarding Agent",
    layer: "cfm",
  },
  {
    container: "health-dataspace-cfm-registration-agent",
    component: "Registration Agent",
    layer: "cfm",
  },
  {
    container: "health-dataspace-postgres",
    component: "PostgreSQL",
    layer: "infrastructure",
  },
  {
    container: "health-dataspace-nats",
    component: "NATS",
    layer: "infrastructure",
  },
  {
    container: "health-dataspace-neo4j",
    component: "Neo4j",
    layer: "infrastructure",
  },
  {
    container: "health-dataspace-neo4j-proxy",
    component: "Neo4j Proxy",
    layer: "infrastructure",
  },
  {
    container: "health-dataspace-traefik",
    component: "Traefik",
    layer: "infrastructure",
  },
  {
    container: "health-dataspace-ui",
    component: "UI",
    layer: "infrastructure",
  },
];
 
// ---------------------------------------------------------------------------
// Docker container stats parsing
// ---------------------------------------------------------------------------
 
interface DockerContainer {
  Id: string;
  Names: string[];
  State: string;
  Status: string;
}
 
interface DockerStats {
  cpu_stats: {
    cpu_usage: { total_usage: number };
    system_cpu_usage: number;
    online_cpus: number;
  };
  precpu_stats: {
    cpu_usage: { total_usage: number };
    system_cpu_usage: number;
  };
  memory_stats: {
    usage: number;
    limit: number;
    stats?: { cache?: number };
  };
}
 
interface DockerInspect {
  State: {
    Health?: {
      Status: string;
      Log?: { Output: string; ExitCode: number; End: string }[];
    };
    Status: string;
    StartedAt: string;
  };
}
 
function calcCpuPercent(stats: DockerStats): number {
  const cpuDelta =
    stats.cpu_stats.cpu_usage.total_usage -
    stats.precpu_stats.cpu_usage.total_usage;
  const systemDelta =
    stats.cpu_stats.system_cpu_usage - stats.precpu_stats.system_cpu_usage;
  const numCpus = stats.cpu_stats.online_cpus || 1;
  Eif (systemDelta > 0 && cpuDelta >= 0) {
    return (cpuDelta / systemDelta) * numCpus * 100;
  }
  return 0;
}
 
function calcMemUsage(stats: DockerStats): {
  usedMB: number;
  limitMB: number;
  percent: number;
} {
  const cache = stats.memory_stats.stats?.cache || 0;
  const used = stats.memory_stats.usage - cache;
  const limit = stats.memory_stats.limit;
  return {
    usedMB: Math.round((used / 1024 / 1024) * 10) / 10,
    limitMB: Math.round((limit / 1024 / 1024) * 10) / 10,
    percent: limit > 0 ? Math.round((used / limit) * 1000) / 10 : 0,
  };
}
 
// ---------------------------------------------------------------------------
// Component info result type
// ---------------------------------------------------------------------------
 
interface ComponentInfo {
  container: string;
  component: string;
  layer: string;
  status: "healthy" | "unhealthy" | "running" | "stopped" | "unknown";
  uptime: string;
  cpu: number;
  mem: { usedMB: number; limitMB: number; percent: number };
}
 
interface ParticipantInfo {
  id: string;
  displayName: string;
  organization: string;
  role: string;
  did: string;
  state: string;
  profileCount: number;
}
 
// ---------------------------------------------------------------------------
// ACA topology mapping (subset of the full Docker SERVICE_MAP — only the apps
// actually deployed on Azure Container Apps via scripts/azure/*.sh)
// ---------------------------------------------------------------------------
 
interface AcaMapping {
  component: string;
  layer: "edc-core" | "identity" | "cfm" | "infrastructure";
}
 
const ACA_SERVICE_MAP: Record<string, AcaMapping> = {
  "mvhd-controlplane": { component: "Control Plane", layer: "edc-core" },
  "mvhd-dp-fhir": { component: "Data Plane FHIR", layer: "edc-core" },
  "mvhd-dp-omop": { component: "Data Plane OMOP", layer: "edc-core" },
  "mvhd-identityhub": { component: "Identity Hub", layer: "identity" },
  "mvhd-issuerservice": { component: "Issuer Service", layer: "identity" },
  "mvhd-keycloak": { component: "Keycloak", layer: "identity" },
  "mvhd-vault": { component: "Vault", layer: "identity" },
  "mvhd-tenant-mgr": { component: "Tenant Manager", layer: "cfm" },
  "mvhd-provision-mgr": { component: "Provision Manager", layer: "cfm" },
  "mvhd-postgres": { component: "PostgreSQL", layer: "infrastructure" },
  "mvhd-nats": { component: "NATS", layer: "infrastructure" },
  "mvhd-neo4j": { component: "Neo4j", layer: "infrastructure" },
  "mvhd-neo4j-proxy": { component: "Neo4j Proxy", layer: "infrastructure" },
  "mvhd-ui": { component: "UI", layer: "infrastructure" },
};
 
/**
 * Enumerate Container Apps in the configured resource group and populate the
 * `components` array with the same shape Docker would produce, using Azure
 * Monitor metrics instead of Docker stats.
 */
async function loadAcaComponents(
  components: ComponentInfo[],
): Promise<boolean> {
  const subscriptionId = azureSubscriptionId();
  const resourceGroup = azureResourceGroup();
  if (!subscriptionId || !resourceGroup) return false;
 
  let apps: Awaited<ReturnType<typeof listContainerApps>>;
  try {
    apps = await listContainerApps(subscriptionId, resourceGroup);
  } catch (err) {
    console.warn("ARM listContainerApps failed:", err);
    return false;
  }
 
  await Promise.all(
    apps.map(async (app) => {
      const mapping = ACA_SERVICE_MAP[app.name];
      if (!mapping) return;
 
      const container = app.properties.template?.containers?.[0];
      const cpuReservation = container?.resources?.cpu ?? 0;
      const memReservationBytes = parseMemoryToBytes(
        container?.resources?.memory,
      );
 
      let sample;
      try {
        sample = await getContainerAppMetrics(
          subscriptionId,
          resourceGroup,
          app.name,
        );
      } catch {
        sample = null;
      }
 
      const runningStatus =
        app.properties.runningStatus ?? app.properties.provisioningState ?? "";
      const status: ComponentInfo["status"] = /running/i.test(runningStatus)
        ? "running"
        : /stopped|stop/i.test(runningStatus)
          ? "stopped"
          : "unknown";
 
      // CPU %: Azure gives UsageNanoCores; divide by cpuReservation (vCPUs).
      // If reservation is present, rescale to "% of reservation"; else keep raw.
      const rawCpuPct = sample?.cpuPercent ?? 0;
      const cpu =
        cpuReservation > 0
          ? Math.round((rawCpuPct / cpuReservation) * 100) / 100
          : rawCpuPct;
 
      // memPercent field from azure-arm is actually bytes; convert.
      const usedBytes = sample?.memPercent ?? 0;
      const usedMB = Math.round((usedBytes / 1024 / 1024) * 10) / 10;
      const limitMB = Math.round((memReservationBytes / 1024 / 1024) * 10) / 10;
      const memPct =
        limitMB > 0 ? Math.round((usedMB / limitMB) * 1000) / 10 : 0;
 
      components.push({
        container: app.name,
        component: mapping.component,
        layer: mapping.layer,
        status,
        uptime: "—",
        cpu,
        mem: { usedMB, limitMB, percent: memPct },
      });
    }),
  );
 
  return true;
}
 
// ---------------------------------------------------------------------------
// GET /api/admin/components
// ---------------------------------------------------------------------------
 
export async function GET() {
  const session = await getServerSession(authOptions);
  const roles = (session as { roles?: string[] } | null)?.roles ?? [];
  Iif (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  Iif (!roles.includes("EDC_ADMIN")) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }
 
  const result = await cached(
    "admin-components",
    CACHE_TTL_MS,
    buildComponentsResponse,
  );
  return NextResponse.json(result);
}
 
async function buildComponentsResponse() {
  const components: ComponentInfo[] = [];
  const participants: ParticipantInfo[] = [];
  let dockerAvailable = false;
  let metricsSource: "docker" | "azure-monitor" | "none" = "none";
 
  // 1a) Azure Container Apps path — use Azure Monitor via managed identity.
  //     Skips the Docker socket entirely (not available on ACA).
  Iif (isAzureDeployment()) {
    const ok = await loadAcaComponents(components);
    if (ok && components.length > 0) {
      dockerAvailable = true; // UI flag: "metrics are available"
      metricsSource = "azure-monitor";
    }
  }
 
  // 1b) Docker Engine API fallback (local dev / single-VM deployment)
  Eif (metricsSource === "none") {
    try {
      const containers = await dockerGet<DockerContainer[]>(
        "/containers/json?all=true&filters=" +
          encodeURIComponent(JSON.stringify({ name: ["health-dataspace"] })),
      );
      dockerAvailable = true;
 
      await Promise.all(
        SERVICE_MAP.map(async (svc) => {
          const container = containers.find((c) =>
            c.Names.some((n) => n === `/${svc.container}`),
          );
          if (!container) {
            components.push({
              ...svc,
              status: "stopped",
              uptime: "—",
              cpu: 0,
              mem: { usedMB: 0, limitMB: 0, percent: 0 },
            });
            return;
          }
 
          // Get inspect for health + uptime
          let healthStatus: ComponentInfo["status"] = "running";
          let uptime = "—";
          try {
            const inspect = await dockerGet<DockerInspect>(
              `/containers/${container.Id}/json`,
            );
            if (inspect.State.Health?.Status) {
              healthStatus = inspect.State.Health
                .Status as ComponentInfo["status"];
            }
            const started = new Date(inspect.State.StartedAt);
            const diffMs = Date.now() - started.getTime();
            const hours = Math.floor(diffMs / 3600000);
            const mins = Math.floor((diffMs % 3600000) / 60000);
            uptime = hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
          } catch {
            /* ignore inspect failures */
          }
 
          // Get stats (one-shot, non-streaming)
          let cpu = 0;
          let mem = { usedMB: 0, limitMB: 0, percent: 0 };
          try {
            const stats = await dockerGet<DockerStats>(
              `/containers/${container.Id}/stats?stream=false`,
            );
            cpu = Math.round(calcCpuPercent(stats) * 100) / 100;
            mem = calcMemUsage(stats);
          } catch {
            /* ignore stats failures */
          }
 
          components.push({ ...svc, status: healthStatus, uptime, cpu, mem });
        }),
      );
    } catch {
      // Docker socket not available — fall back to unknown topology
      const fallbackMap = isAzureDeployment()
        ? Object.entries(ACA_SERVICE_MAP).map(([container, m]) => ({
            container,
            component: m.component,
            layer: m.layer,
          }))
        : SERVICE_MAP;
      for (const svc of fallbackMap) {
        components.push({
          ...svc,
          status: "unknown",
          uptime: "—",
          cpu: 0,
          mem: { usedMB: 0, limitMB: 0, percent: 0 },
        });
      }
    }
  }
 
  // 2) Fetch participant data from CFM
  try {
    const tenants =
      await edcClient.tenant<
        { id: string; version: number; properties: Record<string, string> }[]
      >("/v1alpha1/tenants");
 
    let edcParticipants: { "@id": string; identity: string; state: string }[] =
      [];
    try {
      edcParticipants = await edcClient.management<
        { "@id": string; identity: string; state: string }[]
      >("/v5alpha/participants");
    } catch {
      /* auth may be unavailable */
    }
 
    for (const t of tenants) {
      let profiles: unknown[] = [];
      try {
        profiles = await edcClient.tenant<unknown[]>(
          `/v1alpha1/tenants/${t.id}/participant-profiles`,
        );
      } catch {
        /* no profiles */
      }
 
      // Find matching EDC participant context
      const ctxId = (profiles as { participantContextId?: string }[])?.[0]
        ?.participantContextId;
      const ctx = edcParticipants.find((p) => p["@id"] === ctxId);
 
      // Extract DID from profile identifier (URL-encoded), EDC identity, or tenant property
      const profileDid = (profiles as { identifier?: string }[])?.[0]
        ?.identifier;
      const decodedDid = profileDid
        ? decodeURIComponent(profileDid)
        : undefined;
 
      participants.push({
        id: t.id,
        displayName: t.properties?.displayName || t.id,
        organization: t.properties?.organization || "—",
        role: t.properties?.ehdsParticipantType || t.properties?.role || "—",
        did: ctx?.identity || decodedDid || t.properties?.did || "—",
        state: ctx?.state || "—",
        profileCount: profiles.length,
      });
    }
  } catch (err) {
    console.warn("Could not fetch participant data from CFM:", err);
  }
 
  // Neo4j fallback — when CFM is unreachable (e.g. Azure deployment without
  // tenant-manager) the participants array is empty. Backfill from Neo4j so
  // the /admin/components page still shows the seeded dataspace members.
  if (participants.length === 0) {
    try {
      const neoRows = await runQuery<{
        id: string;
        name: string;
        type: string;
        did: string;
      }>(
        `MATCH (p:Participant)
         WHERE p.name IS NOT NULL AND p.name <> ''
         RETURN DISTINCT
                coalesce(p.participantId, p.id)      AS id,
                p.name                               AS name,
                coalesce(p.participantType, '—')     AS type,
                coalesce(p.did, p.participantId, '—') AS did
         ORDER BY p.name`,
      );
      for (const row of neoRows) {
        participants.push({
          id: row.id,
          displayName: row.name,
          organization: row.name,
          role: row.type,
          did: row.did,
          state: "SEEDED",
          profileCount: 0,
        });
      }
    } catch (neoErr) {
      console.warn("Neo4j participant fallback failed:", neoErr);
    }
  }
 
  // Sort components by layer order then name
  const layerOrder = { "edc-core": 0, identity: 1, cfm: 2, infrastructure: 3 };
  components.sort(
    (a, b) =>
      (layerOrder[a.layer as keyof typeof layerOrder] ?? 9) -
        (layerOrder[b.layer as keyof typeof layerOrder] ?? 9) ||
      a.component.localeCompare(b.component),
  );
 
  const deploymentTarget = isAzureDeployment()
    ? "azure"
    : dockerAvailable
      ? "docker"
      : "unknown";
 
  return {
    timestamp: new Date().toISOString(),
    dockerAvailable,
    metricsSource,
    deploymentTarget,
    components,
    participants,
  };
}