vmService.js•2.63 kB
const { ComputeManagementClient } = require('@azure/arm-compute');
const azureConfig = require('../config/azure');
/**
 * Serviço para monitorar Virtual Machines (VMs) da Azure
 */
class VMService {
  constructor() {
    this.client = null;
  }
  getClient() {
    if (!this.client) {
      this.client = new ComputeManagementClient(
        azureConfig.getCredential(),
        azureConfig.getSubscriptionId()
      );
    }
    return this.client;
  }
  /**
   * Lista todas as VMs em um grupo de recursos
   */
  async listVMsByResourceGroup(resourceGroupName) {
    try {
      const client = this.getClient();
      const vms = [];
      for await (const vm of client.virtualMachines.list(resourceGroupName)) {
        vms.push(vm);
      }
      return vms;
    } catch (error) {
      throw new Error(`Erro ao listar VMs: ${error.message}`);
    }
  }
  /**
   * Lista todas as VMs na subscription
   */
  async listAllVMs() {
    try {
      const client = this.getClient();
      const vms = [];
      for await (const vm of client.virtualMachines.listAll()) {
        vms.push(vm);
      }
      return vms;
    } catch (error) {
      throw new Error(`Erro ao listar todas as VMs: ${error.message}`);
    }
  }
  /**
   * Obtém detalhes de uma VM específica
   */
  async getVM(resourceGroupName, vmName) {
    try {
      const client = this.getClient();
      const vm = await client.virtualMachines.get(
        resourceGroupName,
        vmName,
        { expand: 'instanceView' }
      );
      return vm;
    } catch (error) {
      throw new Error(`Erro ao obter VM ${vmName}: ${error.message}`);
    }
  }
  /**
   * Obtém o status de uma VM
   */
  async getVMStatus(resourceGroupName, vmName) {
    try {
      const vm = await this.getVM(resourceGroupName, vmName);
      const statuses = vm.instanceView?.statuses || [];
      return {
        name: vm.name,
        location: vm.location,
        vmSize: vm.hardwareProfile?.vmSize,
        osType: vm.storageProfile?.osDisk?.osType,
        provisioningState: vm.provisioningState,
        powerState: this.extractPowerState(statuses),
        statuses: statuses.map(s => ({
          code: s.code,
          level: s.level,
          displayStatus: s.displayStatus,
          message: s.message
        }))
      };
    } catch (error) {
      throw new Error(`Erro ao obter status da VM ${vmName}: ${error.message}`);
    }
  }
  extractPowerState(statuses) {
    const powerStatus = statuses.find(s => s.code?.startsWith('PowerState/'));
    return powerStatus ? powerStatus.displayStatus : 'Unknown';
  }
}
module.exports = new VMService();