cleanupOrphanedContainers function

Future<void> cleanupOrphanedContainers(
  1. String workerId
)

Implementation

Future<void> cleanupOrphanedContainers(String workerId) async {
  try {
    _log.info('Cleaning orphaned containers...');
    final prefix = 'openci-$workerId-';

    final result = await Process.run('docker', [
      'ps',
      '-a',
      '--format',
      '{{.Names}}',
      '--filter',
      'name=$prefix',
    ]);

    if (result.exitCode != 0) return;

    final containers = LineSplitter.split(
      result.stdout.toString(),
    ).where((name) => name.isNotEmpty).toList();

    for (final container in containers) {
      _log.info('Removing orphaned container: $container');
      await stopAndRemoveContainer(container);
    }

    if (containers.isNotEmpty) {
      _log.info('Removed ${containers.length} orphaned container(s)');
    }
  } catch (e, s) {
    _log.severe('Error cleaning up orphaned containers: $e');
    await Sentry.captureException(e, stackTrace: s);
  }
}