1313# See the License for the specific language governing permissions and
1414# limitations under the License.
1515#
16- import time
1716from typing import Dict , List , Optional , Set
1817
1918from granulate_utils .containers .client import ContainersClient
2625
2726logger = get_logger_adapter (__name__ )
2827
29- NEWLY_CREATED_CONTAINER_AGE_IN_SECONDS = 3
28+ _containers_client : Optional [ ContainersClient ] = None
3029
3130
3231class ContainerNamesClient :
3332 def __init__ (self ) -> None :
33+ global _containers_client
3434 try :
35- self ._containers_client : Optional [ContainersClient ] = ContainersClient ()
36- logger .info (f"Discovered container runtimes: { self ._containers_client .get_runtimes ()} " )
35+ if _containers_client is None :
36+ _containers_client = ContainersClient ()
37+ logger .info (f"Discovered container runtimes: { _containers_client .get_runtimes ()} " )
3738 except NoContainerRuntimesError :
3839 logger .warning (
3940 "Could not find a Docker daemon or CRI-compatible daemon, profiling data will not"
4041 " include the container names. If you do have a containers runtime and it's not supported,"
4142 " please open a new issue here:"
4243 " https://github.com/Granulate/gprofiler/issues/new"
4344 )
44- self ._containers_client = None
4545
4646 self ._pid_to_container_name_cache : Dict [int , str ] = {}
4747 self ._current_container_names : Set [str ] = set ()
@@ -56,7 +56,7 @@ def container_names(self) -> List[str]:
5656 return list (self ._current_container_names )
5757
5858 def get_container_name (self , pid : int ) -> str :
59- if self . _containers_client is None :
59+ if _containers_client is None :
6060 return ""
6161
6262 if not valid_perf_pid (pid ):
@@ -80,9 +80,6 @@ def _safely_get_process_container_name(self, pid: int) -> Optional[str]:
8080 container_id = get_process_container_id (process )
8181 if container_id is None :
8282 return None
83- # If the container is newly created, we wait a bit to make sure the container is available
84- if time .time () - process .create_time () <= NEWLY_CREATED_CONTAINER_AGE_IN_SECONDS :
85- time .sleep (2 )
8683 except NoSuchProcess :
8784 return None
8885 return self ._get_container_name (container_id )
@@ -110,5 +107,5 @@ def _get_container_name(self, container_id: str) -> Optional[str]:
110107 def _refresh_container_names_cache (self ) -> None :
111108 # We re-fetch all of the currently running containers, so in order to keep the cache small we clear it
112109 self ._container_id_to_name_cache .clear ()
113- for container in self . _containers_client .list_containers () if self . _containers_client is not None else []:
110+ for container in _containers_client .list_containers () if _containers_client is not None else []:
114111 self ._container_id_to_name_cache [container .id ] = container .name
0 commit comments