| // Package version provides driver version resolution, compatibility checking, and listing. | |
| package version | |
| import ( | |
| "context" | |
| "fmt" | |
| "os" | |
| "path" | |
| "path/filepath" | |
| "regexp" | |
| "strconv" | |
| "strings" | |
| "cos.googlesource.com/cos/tools.git/src/cmd/cos_gpu_installer/deviceinfo" | |
| "cos.googlesource.com/cos/tools.git/src/pkg/cos" | |
| "cos.googlesource.com/cos/tools.git/src/pkg/gpuconfig" | |
| log "github.com/golang/glog" | |
| "github.com/pkg/errors" | |
| ) | |
| const ( | |
| // DefaultVersion is the alias for the default GPU driver version. | |
| DefaultVersion = "default" | |
| // LatestVersion is the alias for the latest GPU driver version. | |
| LatestVersion = "latest" | |
| // MajorGPUDriverArtifactPrefix is the prefix of major GPU driver version artifacts. | |
| MajorGPUDriverArtifactPrefix = "gpu_" | |
| // MajorGPUDriverArtifactSuffix is the suffix of major GPU driver version artifacts. | |
| MajorGPUDriverArtifactSuffix = "_version" | |
| gpuDriverProtoBin = "gpu_driver_versions.bin" | |
| templateGPUDriverFile = "gpu_%s_version" | |
| defaultFilePermission = 0755 | |
| ) | |
| // Fallback defines the supported driver major version range and fallback version for a GPU device. | |
| type Fallback struct { | |
| minMajorVersion int | |
| maxMajorVersion int | |
| fallbackDriverVersion string | |
| } | |
| // Compatible checks compatibility of input driverMajorVersion with Fallback for a GPU device type. | |
| func (f Fallback) Compatible(driverMajorVersion int) bool { | |
| if f.maxMajorVersion != 0 && driverMajorVersion > f.maxMajorVersion { | |
| return false | |
| } | |
| if f.minMajorVersion != 0 && driverMajorVersion < f.minMajorVersion { | |
| return false | |
| } | |
| return true | |
| } | |
| var fallbackMap = map[deviceinfo.GPUType]Fallback{ | |
| // R470 is the last driver family supporting K80 GPU devices. | |
| deviceinfo.K80: { | |
| maxMajorVersion: 470, | |
| minMajorVersion: 450, | |
| fallbackDriverVersion: "R470", | |
| }, | |
| deviceinfo.L4: { | |
| minMajorVersion: 525, | |
| fallbackDriverVersion: "R535", | |
| }, | |
| deviceinfo.H100: { | |
| minMajorVersion: 525, | |
| fallbackDriverVersion: "R535", | |
| }, | |
| } | |
| // UseFallbackMechanism determines whether to use the fallback mechanism when a specified | |
| // GPU driver is not compatible with the GPU device. | |
| func UseFallbackMechanism(driverVersion string, forceFallbackSet, forceFallbackValue bool) bool { | |
| // If user specifies the fallback flag, we don't infer whether to use the fallback mechanism. | |
| if forceFallbackSet { | |
| return forceFallbackValue | |
| } | |
| processedArgVersion := strings.ToLower(strings.TrimSpace(driverVersion)) | |
| // If user doesn't specify the fallback flag, | |
| // return `true` for --version=default or --version=latest or version not specified. | |
| // return `false` if --version=R<major-version> eg. 'R470', 'R525' or --version=<precise-version> eg. '535.129.03', '525.147.05' | |
| if processedArgVersion == DefaultVersion || processedArgVersion == LatestVersion || processedArgVersion == "" { | |
| return true | |
| } | |
| return false | |
| } | |
| // ResolveDriverVersion resolves the target driver version using either the protobuf metadata | |
| // or legacy GCS version artifacts, applying compatibility and fallback checks. | |
| func ResolveDriverVersion(ctx context.Context, downloader cos.ArtifactsDownloader, gpuType deviceinfo.GPUType, hostInstallDir, argVersion string, useProto, useFallback bool) (string, error) { | |
| versionInput := argVersion | |
| if useProto { | |
| resolved, err := GetDriverVersionFromProto(ctx, downloader, gpuType, hostInstallDir, argVersion, useFallback) | |
| if err != nil { | |
| return "", fmt.Errorf("failed to get %s driver version with error: %w", versionInput, err) | |
| } | |
| if gpuType == deviceinfo.Others { | |
| log.Warningf("Warning: the GPU device is not recognized by the cos-gpu-installer, "+ | |
| "the GPU driver: %s we are installing may not compatible with the current GPU device. "+ | |
| "Please go to https://cloud.google.com/container-optimized-os/docs/how-to/run-gpus to see the supported GPU devices on COS.", resolved) | |
| } | |
| if gpuType == deviceinfo.NO_GPU { | |
| log.Warningf("Warning: the GPU device is not detected by the cos-gpu-installer, "+ | |
| "the GPU driver: %s we are installing may not compatible on the GPUs this image is being preloaded for.", resolved) | |
| } | |
| return resolved, nil | |
| } | |
| resolved, err := GetDriverVersion(ctx, downloader, argVersion) | |
| if err != nil { | |
| return "", fmt.Errorf("failed to get %s driver version with error: %w", versionInput, err) | |
| } | |
| resolved, err = CheckDriverCompatibility(ctx, downloader, gpuType, resolved, useFallback) | |
| if err != nil { | |
| return "", errors.Wrap(err, "failed to check driver compatibility") | |
| } | |
| return resolved, nil | |
| } | |
| // GetDriverVersionFromProto resolves the GPU driver version from the downloaded or preloaded proto. | |
| func GetDriverVersionFromProto(ctx context.Context, downloader cos.ArtifactsDownloader, gpuType deviceinfo.GPUType, gpuInstallDir, argVersion string, fallback bool) (string, error) { | |
| gpuProtoContent, err := DownloadGPUDriverVersionsProto(ctx, downloader, gpuInstallDir) | |
| if err != nil { | |
| return "", fmt.Errorf("Failed to download and read GPU driver versions proto with error: %v", err) | |
| } | |
| return gpuconfig.GetGPUDriverVersion(gpuProtoContent, gpuType.String(), argVersion, fallback) | |
| } | |
| // GetDriverVersion resolves the GPU driver version from legacy GCS version files. | |
| func GetDriverVersion(ctx context.Context, downloader cos.ArtifactsDownloader, argVersion string) (string, error) { | |
| processedArgVersion := strings.ToLower(strings.TrimSpace(argVersion)) | |
| if processedArgVersion == "" || processedArgVersion == DefaultVersion { | |
| // install the default version. | |
| return GetGPUDriverVersion(ctx, downloader, DefaultVersion) | |
| } | |
| if processedArgVersion == LatestVersion { | |
| // install the latest version. | |
| return GetGPUDriverVersion(ctx, downloader, LatestVersion) | |
| } | |
| majorVersionPattern := regexp.MustCompile(`^r\d+$`) | |
| if majorVersionPattern.MatchString(processedArgVersion) { | |
| // argVersion is a major version, getting the precise gpu driver version. | |
| driverVersion, err := GetGPUDriverVersion(ctx, downloader, strings.ToUpper(processedArgVersion)) | |
| if err != nil { | |
| return "", errors.Errorf("The input GPU driver major version: %s is invalid, please use `$cos-extensions list gpu` to get the available major driver versions.", argVersion) | |
| } | |
| return driverVersion, nil | |
| } | |
| preciseVersionPattern := regexp.MustCompile(`^\d+(\.\d+){1,2}$`) | |
| if !preciseVersionPattern.MatchString(processedArgVersion) { | |
| // precise version is invalid. | |
| return "", errors.Errorf("The input GPU driver version: %s is invalid, please use `$cos-extensions list gpu` to get the available GPU driver versions.", argVersion) | |
| } | |
| // argVersion is an actual version, return it as-is. | |
| return argVersion, nil | |
| } | |
| // CheckDriverCompatibility checks if driverVersion is compatible with gpuType and applies fallback if enabled. | |
| func CheckDriverCompatibility(ctx context.Context, downloader cos.ArtifactsDownloader, gpuType deviceinfo.GPUType, driverVersion string, useFallback bool) (string, error) { | |
| driverMajorVersion, err := strconv.Atoi(strings.Split(driverVersion, ".")[0]) | |
| if err != nil { | |
| return "", errors.Wrap(err, "failed to get driver major version") | |
| } | |
| fallback, found := fallbackMap[gpuType] | |
| if found && !fallback.Compatible(driverMajorVersion) { | |
| if !useFallback { | |
| return "", fmt.Errorf("driver version %s is not compatible with %s GPU device, "+ | |
| "please use a compatible driver, or consider forcing a fallback using `--force-fallback=true` for the installer to select a compatible driver for the device", driverVersion, gpuType) | |
| } | |
| log.Warningf("\n\nDriver version %s doesn't support %s GPU devices.\n\n", driverVersion, gpuType) | |
| fallbackVersion, err := GetGPUDriverVersion(ctx, downloader, fallback.fallbackDriverVersion) | |
| if err != nil { | |
| return "", errors.Wrap(err, "failed to get fallback driver") | |
| } | |
| log.Warningf("\n\nUsing driver version %s for %s GPU compatibility.\n\n", fallbackVersion, gpuType) | |
| return fallbackVersion, nil | |
| } | |
| return driverVersion, nil | |
| } | |
| // findPreloadedProto searches subdirectories of dir for a preloaded gpuDriverProtoBin. | |
| func findPreloadedProto(dir string) string { | |
| entries, err := os.ReadDir(dir) | |
| if err != nil { | |
| return "" | |
| } | |
| for _, entry := range entries { | |
| if !entry.IsDir() { | |
| continue | |
| } | |
| p := filepath.Join(dir, entry.Name(), gpuDriverProtoBin) | |
| if _, err := os.Stat(p); err == nil { | |
| return p | |
| } | |
| } | |
| return "" | |
| } | |
| // DownloadGPUDriverVersionsProto returns the content of gpuDriverProtoBin. | |
| // It searches gpuInstallDir and its subdirectories (for preloaded driver installations) | |
| // before falling back to downloading from the GCS bucket. | |
| func DownloadGPUDriverVersionsProto(ctx context.Context, downloader cos.ArtifactsDownloader, gpuInstallDir string) ([]byte, error) { | |
| destFullPath := filepath.Join(gpuInstallDir, gpuDriverProtoBin) | |
| if _, err := os.Stat(destFullPath); err == nil { | |
| log.Infof("Found GPU driver version proto: %s, skip downloading", destFullPath) | |
| return os.ReadFile(destFullPath) | |
| } else if !os.IsNotExist(err) { | |
| return nil, fmt.Errorf("error checking %s : %v", destFullPath, err) | |
| } | |
| if subPath := findPreloadedProto(gpuInstallDir); subPath != "" { | |
| log.Infof("Found GPU driver version proto in %s, skip downloading", subPath) | |
| return os.ReadFile(subPath) | |
| } | |
| if err := os.MkdirAll(gpuInstallDir, defaultFilePermission); err != nil { | |
| return nil, fmt.Errorf("failed to create %s with error: %v", gpuInstallDir, err) | |
| } | |
| if err := downloader.DownloadArtifact(ctx, gpuInstallDir, gpuDriverProtoBin); err != nil { | |
| return nil, fmt.Errorf("failed to download %s from GCS bucket with error: %v", gpuDriverProtoBin, err) | |
| } | |
| log.Infof("Successfully downloaded %s from GCS bucket.", gpuDriverProtoBin) | |
| return os.ReadFile(destFullPath) | |
| } | |
| // GetGPUDriverVersion gets the supplied GPU driver version. | |
| // Supports "default", "latest", "R470", "R525" aliases. | |
| func GetGPUDriverVersion(ctx context.Context, downloader cos.ArtifactsDownloader, alias string) (string, error) { | |
| log.Infof("Getting the %s GPU driver version", alias) | |
| content, err := downloader.GetArtifact(ctx, fmt.Sprintf(templateGPUDriverFile, alias)) | |
| if err != nil { | |
| return "", errors.Wrapf(err, "failed to get %s GPU driver version", alias) | |
| } | |
| return strings.Trim(string(content), "\n "), nil | |
| } | |
| // DownloadGPUDriverVersionArtifacts fetches all the gpu_xx_version files where the key is the file name and the value is the content. | |
| // E.g. | |
| // gpu_default_version -> 535.129.03, | |
| // gpu_R470_version -> 470.223.02, | |
| // gpu_R535_version -> 535.129.03, | |
| func DownloadGPUDriverVersionArtifacts(ctx context.Context, downloader cos.ArtifactsDownloader) (map[string]string, error) { | |
| gpuArtifacts, err := downloader.ListArtifacts(ctx, MajorGPUDriverArtifactPrefix) | |
| if err != nil { | |
| return nil, fmt.Errorf("error happens when listing artifacts with prefix: %s: %w", MajorGPUDriverArtifactPrefix, err) | |
| } | |
| var gpuDriverMajorVersionArtifactsContentMap = map[string]string{} | |
| for _, gpuArtifact := range gpuArtifacts { | |
| if strings.HasSuffix(gpuArtifact, MajorGPUDriverArtifactSuffix) { | |
| gpuArtifactName := path.Base(gpuArtifact) | |
| content, err := downloader.GetArtifact(ctx, gpuArtifactName) | |
| if err != nil { | |
| return nil, errors.Wrapf(err, "failed to download artifact: %s", gpuArtifact) | |
| } | |
| gpuDriverMajorVersionArtifactsContentMap[gpuArtifactName] = strings.Trim(string(content), "\n ") | |
| } | |
| } | |
| return gpuDriverMajorVersionArtifactsContentMap, nil | |
| } |