blob: ed4a57c781bafa342d2df4d6dd95f944de37b296 [file]
// Package installer provides functionality to install GPU drivers.
package installer
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"cos.googlesource.com/cos/tools.git/src/cmd/cos_gpu_installer/deviceinfo"
"cos.googlesource.com/cos/tools.git/src/cmd/cos_gpu_installer/features"
"cos.googlesource.com/cos/tools.git/src/cmd/cos_gpu_installer/internal/version"
"cos.googlesource.com/cos/tools.git/src/pkg/cos"
"cos.googlesource.com/cos/tools.git/src/pkg/modules"
log "github.com/golang/glog"
"github.com/pkg/errors"
)
const (
gpuInstallDirContainer = "/usr/local/nvidia"
defaultFilePermission = 0755
// DefaultVersion is the alias for the default GPU driver version.
DefaultVersion = version.DefaultVersion
// LatestVersion is the alias for the latest GPU driver version.
LatestVersion = version.LatestVersion
// MajorGPUDriverArtifactPrefix is the prefix of major GPU driver version artifacts.
MajorGPUDriverArtifactPrefix = version.MajorGPUDriverArtifactPrefix
// MajorGPUDriverArtifactSuffix is the suffix of major GPU driver version artifacts.
MajorGPUDriverArtifactSuffix = version.MajorGPUDriverArtifactSuffix
)
// DownloadGPUDriverVersionsProto delegates to version.DownloadGPUDriverVersionsProto.
func DownloadGPUDriverVersionsProto(ctx context.Context, downloader cos.ArtifactsDownloader, gpuInstallDir string) ([]byte, error) {
return version.DownloadGPUDriverVersionsProto(ctx, downloader, gpuInstallDir)
}
// GetGPUDriverVersion delegates to version.GetGPUDriverVersion.
func GetGPUDriverVersion(ctx context.Context, downloader cos.ArtifactsDownloader, alias string) (string, error) {
return version.GetGPUDriverVersion(ctx, downloader, alias)
}
// DownloadGPUDriverVersionArtifacts delegates to version.DownloadGPUDriverVersionArtifacts.
func DownloadGPUDriverVersionArtifacts(ctx context.Context, downloader cos.ArtifactsDownloader) (map[string]string, error) {
return version.DownloadGPUDriverVersionArtifacts(ctx, downloader)
}
// InstallOptions holds the configuration options for running the GPU driver installation workflow.
type InstallOptions struct {
DriverVersion string
HostInstallDir string
ForceFallbackSet bool
ForceFallbackValue bool
UnsignedDriver bool
GDRCopy bool
GCSDownloadBucket string
GCSDownloadPrefix string
NvidiaInstallerURL string
SignatureURL string
TargetGPU string
Debug bool
Test bool
PrepareBuildTools bool
KernelOpen bool
NoVerify bool
SkipNvidiaSmi bool
KernelModuleParams modules.ModuleParameters
NvidiaInstallerURLOpen string
GCSDownloadBucketNvidia string
GCSDownloadPrefixNvidia string
LocalArtifactsDir string
UseRegionalBucket bool
NvidiaFS bool
HostRootPath string
COSGPUConfigJSONPath string
ToolchainPkgDir string
PCIDevicesPath string
}
// RunInstall executes the end-to-end GPU driver installation workflow.
func RunInstall(ctx context.Context, opts InstallOptions) error {
envReader, err := cos.NewEnvReader(opts.HostRootPath)
if err != nil {
return errors.Wrapf(err, "failed to create envReader with host root path %s", opts.HostRootPath)
}
log.V(2).Infof("Running on COS build id %s", envReader.BuildNumber())
fullCOSGPUConfigJSONPath := filepath.Join(opts.HostRootPath, opts.COSGPUConfigJSONPath)
log.Infof("Feature flags initialization")
featureConfig, err := features.InitFlags(fullCOSGPUConfigJSONPath)
if err != nil {
return fmt.Errorf("unable to init feature flags: %w", err)
}
var gpuType = deviceinfo.NO_GPU
if !opts.PrepareBuildTools {
allowTargetFlag := featureConfig.PerGPULabelFeatureFlag && opts.TargetGPU != ""
gpuType, err = deviceinfo.ResolveTargetGPU(opts.TargetGPU, opts.PCIDevicesPath, allowTargetFlag)
if err != nil {
if allowTargetFlag {
return fmt.Errorf("failed to parse the target GPU type: %v", err)
}
if !opts.NoVerify {
return errors.Wrapf(err, "failed to detect GPU type information")
}
log.Infof("No GPU device detected, continue driver preoloading without verification.")
}
}
if arch := envReader.Architecture(); !gpuType.SupportsArch(arch) {
return fmt.Errorf("GPU %s is NOT supported on architecture %s", gpuType, arch)
}
log.Infof("Install GPU driver for device type: %s", gpuType)
// Read value from env NVIDIA_INSTALL_DIR_HOST if the flag is not set. This is to be compatible with old interface.
if opts.HostInstallDir == "" {
opts.HostInstallDir = os.Getenv("NVIDIA_INSTALL_DIR_HOST")
}
hostInstallDir := filepath.Join(opts.HostRootPath, opts.HostInstallDir)
if err := os.MkdirAll(hostInstallDir, 0755); err != nil {
return errors.Wrap(err, "failed to create host install dir")
}
if !(opts.PrepareBuildTools || opts.NoVerify) {
if err := EnsureExecutable(opts.HostInstallDir, opts.HostRootPath); err != nil {
return errors.Wrap(err, "failed to ensure installation directory is executable")
}
}
var downloader *cos.GCSDownloader
if opts.LocalArtifactsDir != "" {
downloader = cos.NewGCSLocalDownloader(nil, envReader, opts.GCSDownloadBucket, opts.GCSDownloadPrefix, opts.GCSDownloadBucketNvidia, opts.GCSDownloadPrefixNvidia, opts.LocalArtifactsDir, opts.UseRegionalBucket)
} else {
downloader = cos.NewGCSDownloader(nil, envReader, opts.GCSDownloadBucket, opts.GCSDownloadPrefix, opts.GCSDownloadBucketNvidia, opts.GCSDownloadPrefixNvidia, opts.UseRegionalBucket)
}
if opts.NvidiaInstallerURL == "" {
useFallback := version.UseFallbackMechanism(opts.DriverVersion, opts.ForceFallbackSet, opts.ForceFallbackValue)
opts.DriverVersion, err = version.ResolveDriverVersion(ctx, downloader, gpuType, hostInstallDir, opts.DriverVersion, featureConfig.PerGPULabelFeatureFlag, useFallback)
if err != nil {
return err
}
installedDriverVersion := GetLoadedNVIDIAKernelModuleVersion("/proc/driver/nvidia/version")
if installedDriverVersion != "" && installedDriverVersion != opts.DriverVersion {
log.Warningf("A different GPU driver with version: %s may be installed, please reboot to install the GPU driver version %s.", installedDriverVersion, opts.DriverVersion)
return nil // A different GPU driver found, we won't proceed with the installation in this case.
}
log.Infof("Installing GPU driver version %s", opts.DriverVersion)
if err := EnableCDMM(gpuType, opts.DriverVersion, opts.KernelModuleParams); err != nil {
return err
}
} else {
log.Infof("Installing GPU driver from %q", opts.NvidiaInstallerURL)
}
if opts.UnsignedDriver {
kernelCmdline, err := ioutil.ReadFile("/proc/cmdline")
if err != nil {
log.Errorf("failed to read kernel command line: %v", err)
}
if cos.CheckKernelModuleSigning(string(kernelCmdline)) {
log.Warning("Current kernel command line does not support unsigned kernel modules. Not enforcing kernel module signing may cause installation fail.")
}
}
kernelDriversPath := filepath.Join(opts.HostRootPath, "/lib/modules", envReader.KernelRelease(), "kernel/drivers")
// Test images ship preloaded driver installations in subdirectories of the
// install dir. Activating the matching one lets the cached installation path
// below run without downloading or building the driver. This also runs when
// there is nothing to activate, to take down an installation activated by an
// earlier run before the driver is installed the regular way.
if !opts.PrepareBuildTools {
if err := ActivatePreloadedInstall(hostInstallDir, envReader.BuildNumber(), opts.DriverVersion, !opts.UnsignedDriver && gpuType.OpenSupported()); err != nil {
return errors.Wrap(err, "failed to activate a preloaded GPU driver installation")
}
}
var cacher *Cacher
isCachedInstall := false
// We only want to cache drivers installed from official sources.
if opts.NvidiaInstallerURL == "" && opts.NvidiaInstallerURLOpen == "" {
cacher = NewCacher(hostInstallDir, envReader.BuildNumber(), opts.DriverVersion)
if isCached, isOpen, err := cacher.IsCached(); isCached && err == nil {
log.V(2).Info("Found cached version, NOT building the drivers.")
if err := ConfigureCachedInstallation(hostInstallDir, kernelDriversPath, opts.Test, isOpen, opts.NoVerify, opts.KernelModuleParams); err != nil {
return errors.Wrap(err, "failed to configure cached installation")
}
isCachedInstall = true
}
}
if !isCachedInstall {
log.V(2).Info("Did not find cached version, installing the drivers...")
// install OSS kernel modules (if available) if device supports
if !opts.UnsignedDriver && gpuType.OpenSupported() {
opts.KernelOpen = gpuType.OpenSupported()
}
prebuiltModulesAvailable, err := PrebuiltModulesAvailable(ctx, downloader, opts.DriverVersion, opts.KernelOpen)
if err != nil {
return errors.Wrap(err, "failed to find prebuilt modules")
}
// skip prebuilt module installation if preparing build tools
if !opts.PrepareBuildTools && prebuiltModulesAvailable {
log.V(2).Info("Found prebuilt kernel modules, installing additional components...")
cleanup, err := ConfigureDriverInstallationDirs(hostInstallDir, envReader.KernelRelease(), envReader.Architecture())
if err != nil {
return errors.Wrap(err, "failed to configure GPU driver installation dirs")
}
defer cleanup()
if err := installDriverPrebuiltModules(ctx, opts, envReader, downloader, kernelDriversPath, gpuType); err != nil {
return err
}
if cacher != nil {
if err := cacher.Cache(true); err != nil {
return errors.Wrap(err, "failed to cache installation")
}
}
} else {
if arch := envReader.Architecture(); arch != "x86_64" {
if opts.PrepareBuildTools {
log.V(2).Infof("No toolchain available to preload for arch: %s", arch)
return nil
}
return fmt.Errorf("precompiled NVIDIA driver modules not available for %s", arch)
}
cleanup, err := ConfigureDriverInstallationDirs(hostInstallDir, envReader.KernelRelease(), envReader.Architecture())
if err != nil {
return errors.Wrap(err, "failed to configure GPU driver installation dirs")
}
defer cleanup()
if err := setupPrecompiledBuildTools(ctx, downloader, opts.ToolchainPkgDir); err != nil {
return err
}
// Skip driver installation if we are only populating build tools cache
if opts.PrepareBuildTools {
return nil
}
if err := installDriverPrecompiled(ctx, opts, envReader, downloader, kernelDriversPath); err != nil {
return err
}
if cacher != nil {
if err := cacher.Cache(false); err != nil {
return errors.Wrap(err, "failed to cache installation")
}
}
}
}
return finalizeInstallation(opts, !isCachedInstall)
}
func finalizeInstallation(opts InstallOptions, isNewInstall bool) error {
if err := VerifyDriverInstallation(opts.NoVerify, opts.Debug, opts.SkipNvidiaSmi); err != nil {
return errors.Wrap(err, "failed to verify GPU driver installation")
}
if opts.GDRCopy {
if err := InstallGDRCopy(opts.NoVerify, opts.KernelModuleParams); err != nil {
return err
}
log.V(1).Info("GDRCopy driver and device node created successfully.")
}
if opts.NvidiaFS {
if err := InstallNvidiaFS(opts.NoVerify, opts.KernelModuleParams); err != nil {
return err
}
log.V(1).Info("Nvidia-FS driver and device node created successfully.")
}
if err := UpdateHostLdCache(opts.HostRootPath, filepath.Join(opts.HostInstallDir, "lib64")); err != nil {
return errors.Wrap(err, "failed to update host ld cache")
}
if isNewInstall {
log.Info("Finished installing the drivers.")
}
if !(opts.PrepareBuildTools || opts.NoVerify) {
if err := SetupDaemons(opts.HostInstallDir, opts.HostRootPath); err != nil {
return errors.Wrap(err, "failed to setup daemons")
}
}
return nil
}