2022-11-16 16:38:39 +00:00
|
|
|
package platform
|
|
|
|
|
2022-12-11 06:58:22 +00:00
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
)
|
2022-11-16 16:38:39 +00:00
|
|
|
|
|
|
|
const (
|
|
|
|
PodmanMode = "PODMAN"
|
|
|
|
KubernetesServiceHost = "KUBERNETES_SERVICE_HOST"
|
|
|
|
)
|
|
|
|
|
2024-06-28 11:54:44 +00:00
|
|
|
// ContainerPlatform represent the platform on which the container is running (Docker, Kubernetes)
|
2022-11-16 16:38:39 +00:00
|
|
|
type ContainerPlatform string
|
|
|
|
|
|
|
|
const (
|
2024-09-20 16:00:38 +00:00
|
|
|
// PlatformDocker represent the Docker platform (Unknown)
|
|
|
|
PlatformDocker = ContainerPlatform("Docker")
|
2022-12-11 06:58:22 +00:00
|
|
|
// PlatformDockerStandalone represent the Docker platform (Standalone)
|
|
|
|
PlatformDockerStandalone = ContainerPlatform("Docker Standalone")
|
|
|
|
// PlatformDockerSwarm represent the Docker platform (Swarm)
|
|
|
|
PlatformDockerSwarm = ContainerPlatform("Docker Swarm")
|
2022-11-16 16:38:39 +00:00
|
|
|
// PlatformKubernetes represent the Kubernetes platform
|
|
|
|
PlatformKubernetes = ContainerPlatform("Kubernetes")
|
|
|
|
// PlatformPodman represent the Podman platform (Standalone)
|
|
|
|
PlatformPodman = ContainerPlatform("Podman")
|
|
|
|
)
|
|
|
|
|
|
|
|
// DetermineContainerPlatform will check for the existence of the PODMAN_MODE
|
|
|
|
// or KUBERNETES_SERVICE_HOST environment variable to determine if
|
|
|
|
// the container is running on Podman or inside the Kubernetes platform.
|
|
|
|
// Defaults to Docker otherwise.
|
2024-09-20 16:00:38 +00:00
|
|
|
func DetermineContainerPlatform() ContainerPlatform {
|
2022-11-16 16:38:39 +00:00
|
|
|
podmanModeEnvVar := os.Getenv(PodmanMode)
|
|
|
|
if podmanModeEnvVar == "1" {
|
2024-09-20 16:00:38 +00:00
|
|
|
return PlatformPodman
|
2022-11-16 16:38:39 +00:00
|
|
|
}
|
2023-03-08 02:34:55 +00:00
|
|
|
|
2022-11-16 16:38:39 +00:00
|
|
|
serviceHostKubernetesEnvVar := os.Getenv(KubernetesServiceHost)
|
|
|
|
if serviceHostKubernetesEnvVar != "" {
|
2024-09-20 16:00:38 +00:00
|
|
|
return PlatformKubernetes
|
2022-11-16 16:38:39 +00:00
|
|
|
}
|
2023-03-08 02:34:55 +00:00
|
|
|
|
2022-12-21 16:08:18 +00:00
|
|
|
if !isRunningInContainer() {
|
2024-09-20 16:00:38 +00:00
|
|
|
return ""
|
2022-12-11 06:58:22 +00:00
|
|
|
}
|
|
|
|
|
2024-09-20 16:00:38 +00:00
|
|
|
return PlatformDocker
|
2022-12-11 06:58:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// isRunningInContainer returns true if the process is running inside a container
|
|
|
|
// this code is taken from https://github.com/moby/libnetwork/blob/master/drivers/bridge/setup_bridgenetfiltering.go
|
|
|
|
func isRunningInContainer() bool {
|
|
|
|
_, err := os.Stat("/.dockerenv")
|
2024-06-28 11:54:44 +00:00
|
|
|
|
2022-12-11 06:58:22 +00:00
|
|
|
return !os.IsNotExist(err)
|
2022-11-16 16:38:39 +00:00
|
|
|
}
|