Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

10.9 KB
Raw Blame
import { apiFetchJSON, type APIContextOptions } from '@/utils/apiClient';
import {
  normalizeMonitoredSystemLedgerPreviewResponse,
  type MonitoredSystemLedgerPreviewResponse,
  type MonitoredSystemLedgerRawPreviewResponse,
} from './monitoredSystemLedger';
import {
  arrayOrUndefined,
  finiteNumberOrUndefined,
  optionalTrimmedString,
  strictBoolean,
  trimmedString,
} from './responseUtils';

const VMWARE_CONNECTIONS_PATH = '/api/vmware/connections';

const REDACTED_SECRET = '********';

type RawVMwareConnection = Partial<VMwareConnection>;
type RawVMwareConnectionPollError = Partial<VMwareConnectionPollError>;
type RawVMwareConnectionPoll = Partial<VMwareConnectionPollStatus>;
type RawVMwareConnectionObservedIssue = Partial<VMwareConnectionObservedIssue>;
type RawVMwareConnectionObservedSummary = Partial<VMwareConnectionObservedSummary>;

export interface VMwareConnectionPollError {
  at?: string;
  message?: string;
  category?: string;
}

export interface VMwareConnectionPollStatus {
  intervalSeconds?: number;
  lastAttemptAt?: string;
  lastSuccessAt?: string;
  consecutiveFailures?: number;
  lastError?: VMwareConnectionPollError;
}

export interface VMwareConnectionObservedSummary {
  collectedAt?: string;
  hosts: number;
  vms: number;
  datastores: number;
  networks: number;
  viRelease?: string;
  degraded?: boolean;
  issueCount?: number;
  issues?: VMwareConnectionObservedIssue[];
}

export interface VMwareConnectionObservedIssue {
  stage?: string;
  category?: string;
  message?: string;
  occurrences?: number;
}

export interface VMwareConnection {
  id: string;
  name: string;
  host: string;
  port?: number;
  username?: string;
  password?: string;
  insecureSkipVerify: boolean;
  enabled: boolean;
  monitorVms: boolean;
  monitorHosts: boolean;
  monitorDatastores: boolean;
  poll?: VMwareConnectionPollStatus;
  observed?: VMwareConnectionObservedSummary;
}

export interface VMwareConnectionInput {
  name?: string;
  host: string;
  port?: number;
  username?: string;
  password?: string;
  insecureSkipVerify?: boolean;
  enabled?: boolean;
  monitorVms?: boolean;
  monitorHosts?: boolean;
  monitorDatastores?: boolean;
}

export interface VMwareConnectionTestResult {
  success: boolean;
  hosts: number;
  vms: number;
  datastores: number;
  networks: number;
  viRelease?: string;
  degraded: boolean;
  issueCount: number;
  issues: VMwareConnectionTestIssue[];
}

export interface VMwareConnectionTestIssue {
  stage?: string;
  entityType?: string;
  entityId?: string;
  category?: string;
  message?: string;
}

type RawVMwareConnectionTestIssue = Partial<VMwareConnectionTestIssue> & {
  entity_type?: unknown;
  entity_id?: unknown;
};

const normalizeVMwareConnectionTestResult = (
  response: Partial<VMwareConnectionTestResult> & {
    issues?: RawVMwareConnectionTestIssue[];
  },
): VMwareConnectionTestResult => ({
  success: strictBoolean(response.success),
  hosts: finiteNumberOrUndefined(response.hosts) ?? 0,
  vms: finiteNumberOrUndefined(response.vms) ?? 0,
  datastores: finiteNumberOrUndefined(response.datastores) ?? 0,
  networks: finiteNumberOrUndefined(response.networks) ?? 0,
  viRelease: optionalTrimmedString(response.viRelease),
  degraded: strictBoolean(response.degraded),
  issueCount: finiteNumberOrUndefined(response.issueCount) ?? 0,
  issues:
    arrayOrUndefined<RawVMwareConnectionTestIssue>(response.issues)?.map((issue) => ({
      stage: optionalTrimmedString(issue.stage),
      entityType: optionalTrimmedString(issue.entityType ?? issue.entity_type),
      entityId: optionalTrimmedString(issue.entityId ?? issue.entity_id),
      category: optionalTrimmedString(issue.category),
      message: optionalTrimmedString(issue.message),
    })) ?? [],
});

const normalizeVMwareConnectionPollError = (
  error: RawVMwareConnectionPollError | undefined,
): VMwareConnectionPollError | undefined => {
  if (!error || typeof error !== 'object') return undefined;
  return {
    at: optionalTrimmedString(error.at),
    message: optionalTrimmedString(error.message),
    category: optionalTrimmedString(error.category),
  };
};

const normalizeVMwareConnectionPoll = (
  poll: RawVMwareConnectionPoll | undefined,
): VMwareConnectionPollStatus | undefined => {
  if (!poll || typeof poll !== 'object') return undefined;
  return {
    intervalSeconds: finiteNumberOrUndefined(poll.intervalSeconds),
    lastAttemptAt: optionalTrimmedString(poll.lastAttemptAt),
    lastSuccessAt: optionalTrimmedString(poll.lastSuccessAt),
    consecutiveFailures: finiteNumberOrUndefined(poll.consecutiveFailures),
    lastError: normalizeVMwareConnectionPollError(poll.lastError),
  };
};

const normalizeVMwareConnectionObservedSummary = (
  observed: RawVMwareConnectionObservedSummary | undefined,
): VMwareConnectionObservedSummary | undefined => {
  if (!observed || typeof observed !== 'object') return undefined;
  return {
    collectedAt: optionalTrimmedString(observed.collectedAt),
    hosts: finiteNumberOrUndefined(observed.hosts) ?? 0,
    vms: finiteNumberOrUndefined(observed.vms) ?? 0,
    datastores: finiteNumberOrUndefined(observed.datastores) ?? 0,
    networks: finiteNumberOrUndefined(observed.networks) ?? 0,
    viRelease: optionalTrimmedString(observed.viRelease),
    degraded: strictBoolean(observed.degraded),
    issueCount: finiteNumberOrUndefined(observed.issueCount),
    issues: arrayOrUndefined<RawVMwareConnectionObservedIssue>(observed.issues)?.map((issue) => ({
      stage: optionalTrimmedString(issue.stage),
      category: optionalTrimmedString(issue.category),
      message: optionalTrimmedString(issue.message),
      occurrences: finiteNumberOrUndefined(issue.occurrences),
    })),
  };
};

const normalizeVMwareConnection = (
  connection: RawVMwareConnection & { test?: RawVMwareConnectionPoll },
): VMwareConnection => ({
  id: trimmedString(connection.id),
  name: optionalTrimmedString(connection.name) ?? '',
  host: trimmedString(connection.host),
  port: finiteNumberOrUndefined(connection.port),
  username: optionalTrimmedString(connection.username),
  password: optionalTrimmedString(connection.password),
  insecureSkipVerify: strictBoolean(connection.insecureSkipVerify),
  enabled: strictBoolean(connection.enabled),
  monitorVms: strictBoolean(connection.monitorVms),
  monitorHosts: strictBoolean(connection.monitorHosts),
  monitorDatastores: strictBoolean(connection.monitorDatastores),
  poll: normalizeVMwareConnectionPoll(connection.poll ?? connection.test),
  observed: normalizeVMwareConnectionObservedSummary(connection.observed),
});

const serializeVMwareConnectionInput = (input: VMwareConnectionInput) => ({
  ...(input.name !== undefined ? { name: input.name } : {}),
  host: input.host,
  ...(input.port !== undefined ? { port: input.port } : {}),
  ...(input.username !== undefined ? { username: input.username } : {}),
  ...(input.password !== undefined ? { password: input.password } : {}),
  ...(input.insecureSkipVerify !== undefined
    ? { insecureSkipVerify: input.insecureSkipVerify }
    : {}),
  ...(input.enabled !== undefined ? { enabled: input.enabled } : {}),
  ...(input.monitorVms !== undefined ? { monitorVms: input.monitorVms } : {}),
  ...(input.monitorHosts !== undefined ? { monitorHosts: input.monitorHosts } : {}),
  ...(input.monitorDatastores !== undefined ? { monitorDatastores: input.monitorDatastores } : {}),
});

export const isRedactedVMwareSecret = (value: string | null | undefined) =>
  (value || '').trim() === REDACTED_SECRET;

export class VMwareAPI {
  static async listConnections(options?: APIContextOptions): Promise<VMwareConnection[]> {
    const response = await (options === undefined
      ? apiFetchJSON<RawVMwareConnection[]>(VMWARE_CONNECTIONS_PATH)
      : apiFetchJSON<RawVMwareConnection[]>(VMWARE_CONNECTIONS_PATH, options));
    const list = arrayOrUndefined<RawVMwareConnection>(response) ?? [];
    return list.map(normalizeVMwareConnection);
  }

  static async createConnection(
    input: VMwareConnectionInput,
    options?: APIContextOptions,
  ): Promise<VMwareConnection> {
    const response = await apiFetchJSON<RawVMwareConnection>(VMWARE_CONNECTIONS_PATH, {
      ...options,
      method: 'POST',
      body: JSON.stringify(serializeVMwareConnectionInput(input)),
    });
    return normalizeVMwareConnection(response);
  }

  static async updateConnection(
    id: string,
    input: VMwareConnectionInput,
    options?: APIContextOptions,
  ): Promise<VMwareConnection> {
    const response = await apiFetchJSON<RawVMwareConnection>(
      `${VMWARE_CONNECTIONS_PATH}/${encodeURIComponent(id)}`,
      {
        ...options,
        method: 'PUT',
        body: JSON.stringify(serializeVMwareConnectionInput(input)),
      },
    );
    return normalizeVMwareConnection(response);
  }

  static async deleteConnection(
    id: string,
    options?: APIContextOptions,
  ): Promise<{ success: boolean; id: string }> {
    return apiFetchJSON(`${VMWARE_CONNECTIONS_PATH}/${encodeURIComponent(id)}`, {
      ...options,
      method: 'DELETE',
    });
  }

  static async testConnection(
    input: VMwareConnectionInput,
    options?: APIContextOptions,
  ): Promise<VMwareConnectionTestResult> {
    const response = await apiFetchJSON<Partial<VMwareConnectionTestResult>>(
      `${VMWARE_CONNECTIONS_PATH}/test`,
      {
        ...options,
        method: 'POST',
        body: JSON.stringify(serializeVMwareConnectionInput(input)),
      },
    );
    return normalizeVMwareConnectionTestResult(response);
  }

  static async testSavedConnection(
    id: string,
    input?: VMwareConnectionInput,
    options?: APIContextOptions,
  ): Promise<VMwareConnectionTestResult> {
    const response = await apiFetchJSON<Partial<VMwareConnectionTestResult>>(
      `${VMWARE_CONNECTIONS_PATH}/${encodeURIComponent(id)}/test`,
      {
        ...options,
        method: 'POST',
        ...(input !== undefined
          ? { body: JSON.stringify(serializeVMwareConnectionInput(input)) }
          : {}),
      },
    );
    return normalizeVMwareConnectionTestResult(response);
  }

  static async previewConnection(
    input: VMwareConnectionInput,
    options?: APIContextOptions,
  ): Promise<MonitoredSystemLedgerPreviewResponse> {
    const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
      `${VMWARE_CONNECTIONS_PATH}/preview`,
      {
        ...options,
        method: 'POST',
        body: JSON.stringify(serializeVMwareConnectionInput(input)),
      },
    );
    return normalizeMonitoredSystemLedgerPreviewResponse(response);
  }

  static async previewSavedConnection(
    id: string,
    input?: VMwareConnectionInput,
    options?: APIContextOptions,
  ): Promise<MonitoredSystemLedgerPreviewResponse> {
    const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
      `${VMWARE_CONNECTIONS_PATH}/${encodeURIComponent(id)}/preview`,
      {
        ...options,
        method: 'POST',
        ...(input !== undefined
          ? { body: JSON.stringify(serializeVMwareConnectionInput(input)) }
          : {}),
      },
    );
    return normalizeMonitoredSystemLedgerPreviewResponse(response);
  }
}