diff --git a/samcli/cli/global_config.py b/samcli/cli/global_config.py index b4f587ce84..f628091ffb 100644 --- a/samcli/cli/global_config.py +++ b/samcli/cli/global_config.py @@ -62,6 +62,9 @@ class GlobalConfig(metaclass=Singleton): # Env var for injecting dir in integration tests _DIR_INJECTION_ENV_VAR: str = "__SAM_CLI_APP_DIR" + # Env var used by docker client to specify which socket to use + DOCKER_HOST_ENV_VAR: str = "DOCKER_HOST" + # Static singleton instance _access_lock: threading.RLock @@ -71,6 +74,7 @@ class GlobalConfig(metaclass=Singleton): _config_data: Optional[Dict[str, Any]] # config_keys that should be flushed to file _persistent_fields: List[str] + docker_host: str def __init__(self): """__init__ should only be called once due to Singleton metaclass""" @@ -79,6 +83,7 @@ def __init__(self): self._config_filename = None self._config_data = None self._persistent_fields = list() + self.docker_host = os.environ.get(GlobalConfig.DOCKER_HOST_ENV_VAR, "") @property def config_dir(self) -> Path: diff --git a/samcli/lib/telemetry/metric.py b/samcli/lib/telemetry/metric.py index 7f3127cf86..5490315379 100644 --- a/samcli/lib/telemetry/metric.py +++ b/samcli/lib/telemetry/metric.py @@ -3,6 +3,7 @@ """ import logging +import os import platform import uuid from dataclasses import dataclass @@ -10,6 +11,7 @@ from pathlib import Path from timeit import default_timer from typing import Any, Dict, Optional +from urllib.parse import urlparse import click @@ -436,6 +438,7 @@ def _add_common_metric_attributes(self): self._data["installationId"] = self._gc.installation_id self._data["sessionId"] = self._session_id self._data["executionEnvironment"] = self._get_execution_environment() + self._data["dockerHost"] = self._get_docker_host() self._data["ci"] = bool(self._cicd_detector.platform()) self._data["pyversion"] = platform.python_version() self._data["samcliVersion"] = samcli_version @@ -476,6 +479,28 @@ def _get_execution_environment(self) -> str: return cicd_platform.name return "CLI" + def _get_docker_host(self) -> str: + """ + Returns the last part of a DOCKER_HOST string. Has conditional logic to properly parse + URLs and local file system paths. If the DOCKER_HOST is not set, returns an empty string. + + Examples: + - unix:///var/run/docker.sock -> docker.sock + - tcp://localhost:1234 -> localhost:1234 + - /var/run/docker.sock -> docker.sock + """ + + parsed = urlparse(self._gc.docker_host) + if not parsed.scheme == '': + if os.path.exists(): + # self._gc.docker_host is a file path + return os.path.basename(os.path.normpath(self._gc.docker_host)) + else: + # self._gc.docker_host is a URI + return os.path.basename(parsed.path) + + return "" + class MetricDataNotList(Exception): pass