detectMachine function

MachineInfo detectMachine({
  1. Map<String, String>? env,
})

Detects the machine's capacity. Reads cgroup limits on Linux so containers are sized by their quota, not the host.

Implementation

MachineInfo detectMachine({Map<String, String>? env}) {
  var cores = io.Platform.numberOfProcessors;
  var cpuContainer = false;
  var memContainer = false;
  int? total;
  int? available;
  try {
    if (io.Platform.isLinux) {
      final cpuV2 = _readText('/sys/fs/cgroup/cpu.max');
      final quotaV1 = _readText('/sys/fs/cgroup/cpu/cpu.cfs_quota_us');
      final periodV1 = _readText('/sys/fs/cgroup/cpu/cpu.cfs_period_us');
      final limit = cpuV2 != null
          ? parseCgroupCpuMax(cpuV2)
          : (quotaV1 != null && periodV1 != null
                ? parseCgroupV1Cpu(quotaV1, periodV1)
                : null);
      if (limit != null && limit < cores) {
        cores = limit;
        cpuContainer = true;
      }
      var (_, hostTotal) = _readProcMeminfo();
      final limitMem = parseCgroupMemoryBytes(
        _readText('/sys/fs/cgroup/memory.max') ??
            _readText('/sys/fs/cgroup/memory/memory.limit_in_bytes') ??
            'max',
      );
      if (limitMem != null) {
        final limitMb = limitMem ~/ (1024 * 1024);
        if (hostTotal == null || limitMb < hostTotal) {
          hostTotal = limitMb;
          memContainer = true;
        }
      }
      total = hostTotal;
      available = readAvailableMemoryMb();
    }
  } on Object {
    // Detection is best-effort; fall through with what was gathered.
  }
  return MachineInfo(
    cores: cores < 1 ? 1 : cores,
    availableMemoryMb: available,
    totalMemoryMb: total,
    isCi: detectCi(env),
    cpuLimitedByContainer: cpuContainer,
    memoryLimitedByContainer: memContainer,
  );
}