From 42328827cf0e2c6bf0f3815cd14f56b500c2f004 Mon Sep 17 00:00:00 2001 From: Lucas Bustamante Date: Wed, 6 Mar 2024 12:17:37 -0300 Subject: [PATCH] Detect running containers that have no environments associated --- .../EnvironmentDanglingCleanup.php | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/src/Environment/EnvironmentDanglingCleanup.php b/src/src/Environment/EnvironmentDanglingCleanup.php index b38c4111..f142c31d 100644 --- a/src/src/Environment/EnvironmentDanglingCleanup.php +++ b/src/src/Environment/EnvironmentDanglingCleanup.php @@ -59,6 +59,7 @@ public function __construct( public function cleanup_dangling(): void { $this->remove_dangling_environments(); $this->detect_dangling_containers_exited(); + $this->detect_dangling_containers_running(); $this->detect_dangling_networks(); $this->detect_dangling_directories(); @@ -206,6 +207,47 @@ protected function detect_dangling_containers_exited(): void { } } + /** + * - Detect running containers that have no environments associated. + */ + protected function detect_dangling_containers_running(): void { + $running_environments = $this->environment_monitor->get(); + + // List the running containers. + $list_process = new Process( [ 'docker', 'container', 'ls', '--format=json', '--filter=status=running', '--filter=name=qit_env_' ] ); + $list_process->run(); + $containers_output = $list_process->getOutput(); + + $lines = explode( "\n", $containers_output ); + + $running_containers = []; + + foreach ( $lines as $line ) { + $c = json_decode( $line, true ); + if ( $c === null ) { + continue; + } + if ( empty( $c['Names'] ) ) { + continue; + } + $container_name = $c['Names']; + + if ( substr( $container_name, 0, strlen( 'qit_env_' ) ) === 'qit_env_' ) { + $running_containers[] = $container_name; + } + } + + foreach ( $running_containers as $container_name ) { + foreach ( $running_environments as $env_info ) { + if ( strpos( $container_name, $env_info->env_id ) !== false ) { + continue 2; + } + } + + $this->dangling_containers[] = 'qit_env_' . $container_name; + } + } + /** * - Checks that all directories in the temp envs directory are in use by a running environment. * - Mark the directory as orphaned if it's not in use by a running environment.