| package installer | |
| import ( | |
| "context" | |
| stderrors "errors" | |
| "fmt" | |
| "io/fs" | |
| "io/ioutil" | |
| "os" | |
| "os/exec" | |
| "path" | |
| "path/filepath" | |
| "sort" | |
| "strings" | |
| "cos.googlesource.com/cos/tools.git/src/cmd/cos_gpu_installer/internal/signing" | |
| "cos.googlesource.com/cos/tools.git/src/pkg/cos" | |
| "cos.googlesource.com/cos/tools.git/src/pkg/modules" | |
| "cos.googlesource.com/cos/tools.git/src/pkg/utils" | |
| log "github.com/golang/glog" | |
| "github.com/pkg/errors" | |
| "golang.org/x/sys/unix" | |
| ) | |
| const ( | |
| precompiledDriverTemplate = "NVIDIA-Linux-x86_64-%s-custom.run" | |
| signedURLKey = "Expires" | |
| ) | |
| var errInstallerFailed = stderrors.New("failed to run GPU driver installer") | |
| // DownloadToInstallDir downloads data from the provided URL to the GPU | |
| // installation directory. It returns the basename of the locally written file. | |
| func DownloadToInstallDir(url, infoStr string) (string, error) { | |
| outputPath := filepath.Join(gpuInstallDirContainer, strings.Split(path.Base(url), "?"+signedURLKey+"=")[0]) | |
| if err := utils.DownloadContentFromURL(url, outputPath, infoStr); err != nil { | |
| return "", fmt.Errorf("failed to download file with description %q from %q and install into %q: %v", infoStr, url, gpuInstallDirContainer, err) | |
| } | |
| return filepath.Base(outputPath), nil | |
| } | |
| // DownloadDriverInstallerV2 downloads GPU driver installer given driver version from COS build artifacts. | |
| func DownloadDriverInstallerV2(ctx context.Context, downloader cos.ExtensionsDownloader, driverVersion string) (string, error) { | |
| log.Infof("Downloading GPU driver installer version %s", driverVersion) | |
| installerFilename := fmt.Sprintf(precompiledDriverTemplate, driverVersion) | |
| err := downloader.DownloadExtensionArtifact(ctx, gpuInstallDirContainer, cos.GPUExtension, installerFilename) | |
| if err != nil { | |
| return "", errors.Wrap(err, "failed to download installer") | |
| } | |
| return installerFilename, nil | |
| } | |
| func setupPrecompiledBuildTools(ctx context.Context, downloader *cos.GCSDownloader, toolchainPkgDir string) error { | |
| if err := cos.SetCompilationEnv(ctx, downloader); err != nil { | |
| return errors.Wrap(err, "failed to set compilation environment variables") | |
| } | |
| if err := remountExecutable(toolchainPkgDir); err != nil { | |
| return fmt.Errorf("failed to remount %q as executable: %v", filepath.Dir(toolchainPkgDir), err) | |
| } | |
| if err := cos.InstallCrossToolchain(ctx, downloader, toolchainPkgDir); err != nil { | |
| return errors.Wrap(err, "failed to install toolchain") | |
| } | |
| return nil | |
| } | |
| func installDriverPrecompiled(ctx context.Context, opts InstallOptions, envReader *cos.EnvReader, downloader *cos.GCSDownloader, kernelDriversPath string) error { | |
| var installerFile string | |
| var err error | |
| if opts.NvidiaInstallerURL == "" { | |
| installerFile, err = DownloadDriverInstallerV2(ctx, downloader, opts.DriverVersion) | |
| if err != nil { | |
| return errors.Wrap(err, "failed to download GPU driver installer") | |
| } | |
| } else { | |
| installerFile, err = DownloadToInstallDir(opts.NvidiaInstallerURL, "Unofficial GPU driver installer") | |
| if err != nil { | |
| return err | |
| } | |
| } | |
| if !opts.UnsignedDriver { | |
| if opts.SignatureURL != "" { | |
| if err := signing.DownloadDriverSignaturesFromURL(opts.SignatureURL); err != nil { | |
| return errors.Wrap(err, "failed to download driver signature") | |
| } | |
| } else { | |
| if err = signing.DownloadDriverSignaturesV2(ctx, downloader, opts.DriverVersion); err != nil { | |
| return errors.Wrap(err, "failed to download driver signature") | |
| } | |
| } | |
| } | |
| if err := RunDriverInstaller(opts.ToolchainPkgDir, installerFile, opts.DriverVersion, envReader.Architecture(), kernelDriversPath, !opts.UnsignedDriver, opts.Test, false, opts.NoVerify, opts.KernelModuleParams); err != nil { | |
| if errors.Is(err, ErrDriverLoad) { | |
| // Drivers were linked, but couldn't load; try again with legacy linking | |
| log.Infof("Failed to load kernel module, err: %v. Retrying driver installation with legacy linking", err) | |
| if err := RunDriverInstaller(opts.ToolchainPkgDir, installerFile, opts.DriverVersion, envReader.Architecture(), kernelDriversPath, !opts.UnsignedDriver, opts.Test, true, opts.NoVerify, opts.KernelModuleParams); err != nil { | |
| return fmt.Errorf("failed to run GPU driver installer: %v", err) | |
| } | |
| } else { | |
| return errors.Wrap(err, "failed to run GPU driver installer") | |
| } | |
| } | |
| return nil | |
| } | |
| func extractPrecompiled(nvidiaDir string) error { | |
| log.Info("Extracting precompiled artifacts...") | |
| precompiledDir := filepath.Join(nvidiaDir, "kernel", "precompiled") | |
| files, err := os.ReadDir(precompiledDir) | |
| if err != nil { | |
| return fmt.Errorf("failed to read %q: %v", precompiledDir, err) | |
| } | |
| var precompiledArchive string | |
| if len(files) == 0 { | |
| return stderrors.New("failed to find precompiled artifacts in this nvidia installer") | |
| } | |
| if len(files) == 1 { | |
| precompiledArchive = filepath.Join(precompiledDir, files[0].Name()) | |
| } | |
| if len(files) > 1 { | |
| var fileNames []string | |
| for _, f := range files { | |
| fileNames = append(fileNames, f.Name()) | |
| } | |
| sort.Strings(fileNames) | |
| log.Warningf("Found multiple precompiled archives in this nvidia installer: %q", strings.Join(fileNames, ",")) | |
| log.Warningf("Using precompiled archive named %q", fileNames[len(fileNames)-1]) | |
| precompiledArchive = filepath.Join(precompiledDir, fileNames[len(fileNames)-1]) | |
| } | |
| cmd := exec.Command(filepath.Join(nvidiaDir, "mkprecompiled"), "--unpack", precompiledArchive, "-o", precompiledDir) | |
| if err := utils.RunCommandAndLogOutput(cmd, false); err != nil { | |
| return fmt.Errorf("failed to unpack precompiled artifacts: %v", err) | |
| } | |
| log.Info("Done extracting precompiled artifacts") | |
| return nil | |
| } | |
| func linkDrivers(toolchainDir, nvidiaDir string) error { | |
| log.Info("Linking drivers...") | |
| var kernelInfo unix.Utsname | |
| if err := unix.Uname(&kernelInfo); err != nil { | |
| return fmt.Errorf("failed to find kernel release info using uname: %v", err) | |
| } | |
| kernelRelease := strings.Trim(string(kernelInfo.Release[:]), "\x00") | |
| // COS 85+ kernels use lld as their linker | |
| linker := filepath.Join(toolchainDir, "bin", "ld.lld") | |
| headersDir := filepath.Join(toolchainDir, "usr", "src", "linux-headers-"+kernelRelease) | |
| linkerScript := filepath.Join(headersDir, "scripts", "module.lds") | |
| linkerScriptExists, err := utils.CheckFileExists(linkerScript) | |
| if err != nil { | |
| return fmt.Errorf("failed to check if %s exists, err: %v", linkerScript, err) | |
| } | |
| if !linkerScriptExists { | |
| // Fallback to module-common.lds, which is used in the 5.4 kernel | |
| linkerScript = filepath.Join(headersDir, "scripts", "module-common.lds") | |
| } | |
| // For kernel 6.12, we also need to link .module-common.o (compiled from | |
| // scripts/module-common.c), which will insert the appropriate vermagic | |
| // string into the modules. | |
| moduleCommonObj := filepath.Join(headersDir, ".module-common.o") | |
| moduleCommonObjExists, err := utils.CheckFileExists(moduleCommonObj) | |
| if err != nil { | |
| return fmt.Errorf("failed to check if %s exists, err: %v", moduleCommonObj, err) | |
| } | |
| nvidiaKernelDir := filepath.Join(nvidiaDir, "kernel") | |
| // Link nvidia.ko | |
| nvidiaObjs := []string{ | |
| filepath.Join(nvidiaKernelDir, "precompiled", "nv-linux.o"), | |
| filepath.Join(nvidiaKernelDir, "nvidia", "nv-kernel.o_binary"), | |
| } | |
| if moduleCommonObjExists { | |
| nvidiaObjs = append(nvidiaObjs, moduleCommonObj) | |
| } | |
| args := append([]string{"-T", linkerScript, "-r", "-o", filepath.Join(nvidiaKernelDir, "precompiled", "nvidia.ko")}, nvidiaObjs...) | |
| cmd := exec.Command(linker, args...) | |
| log.Infof("Running link command: %v", cmd.Args) | |
| if err := utils.RunCommandAndLogOutput(cmd, false); err != nil { | |
| return fmt.Errorf("failed to link nvidia.ko: %v", err) | |
| } | |
| // Link nvidia-modeset.ko | |
| modesetObjs := []string{ | |
| filepath.Join(nvidiaKernelDir, "precompiled", "nv-modeset-linux.o"), | |
| filepath.Join(nvidiaKernelDir, "nvidia-modeset", "nv-modeset-kernel.o_binary"), | |
| } | |
| if moduleCommonObjExists { | |
| modesetObjs = append(modesetObjs, moduleCommonObj) | |
| } | |
| args = append([]string{"-T", linkerScript, "-r", "-o", filepath.Join(nvidiaKernelDir, "precompiled", "nvidia-modeset.ko")}, modesetObjs...) | |
| cmd = exec.Command(linker, args...) | |
| log.Infof("Running link command: %v", cmd.Args) | |
| if err := utils.RunCommandAndLogOutput(cmd, false); err != nil { | |
| return fmt.Errorf("failed to link nvidia-modeset.ko: %v", err) | |
| } | |
| // Move all modules to kernel dir (includes some pre-linked modules, in | |
| // addition to the above linked ones) | |
| if err := filepath.WalkDir(filepath.Join(nvidiaKernelDir, "precompiled"), func(path string, d fs.DirEntry, err error) error { | |
| if err != nil { | |
| return err | |
| } | |
| if d.IsDir() { | |
| return nil | |
| } | |
| if filepath.Ext(path) == ".ko" { | |
| newPath := filepath.Join(nvidiaKernelDir, filepath.Base(path)) | |
| if err := unix.Rename(path, newPath); err != nil { | |
| return fmt.Errorf("failed to move %q to %q: %v", path, newPath, err) | |
| } | |
| } | |
| return nil | |
| }); err != nil { | |
| return fmt.Errorf("failed to copy kernel modules: %v", err) | |
| } | |
| log.Info("Done linking drivers") | |
| return nil | |
| } | |
| func linkDriversLegacy(toolchainDir, nvidiaDir string) error { | |
| log.Info("Linking drivers using legacy method...") | |
| // The legacy linking method needs to use "/usr/bin/ld" as the linker to | |
| // maintain bit-for-bit compatibility with driver signatures. The legacy | |
| // linking method also finds the linker by searching the PATH for "ld". If | |
| // bin/ld is present in the toolchain, rename it temporarily so the legacy | |
| // linking method doesn't use it. | |
| ld := filepath.Join(toolchainDir, "bin", "ld") | |
| if _, err := os.Lstat(ld); !os.IsNotExist(err) { | |
| dst := filepath.Join(toolchainDir, "bin", "ld.orig") | |
| if err := unix.Rename(ld, dst); err != nil { | |
| return fmt.Errorf("failed to rename %q to %q: %v", ld, dst, err) | |
| } | |
| defer func() { | |
| if err := unix.Rename(dst, ld); err != nil { | |
| // At this point, this error is non-fatal. It will become fatal when | |
| // something tries to use bin/ld in the toolchain. At time of writing, | |
| // nothing uses bin/ld after this point. | |
| log.Warningf("Could not restore %q", ld) | |
| } | |
| }() | |
| } | |
| cmd := exec.Command(filepath.Join(nvidiaDir, "nvidia-installer"), | |
| "--utility-prefix="+gpuInstallDirContainer, | |
| "--opengl-prefix="+gpuInstallDirContainer, | |
| "--x-prefix="+gpuInstallDirContainer, | |
| "--install-libglvnd", | |
| "--no-install-compat32-libs", | |
| "--log-file-name="+filepath.Join(gpuInstallDirContainer, "nvidia-installer.log"), | |
| "--silent", | |
| "--accept-license", | |
| ) | |
| cmd.Env = append(cmd.Env, "PATH="+filepath.Join(gpuInstallDirContainer, "bin")+":"+os.Getenv("PATH")) | |
| log.Infof("Installer arguments:\n%v", cmd.Args) | |
| err := utils.RunCommandAndLogOutput(cmd, false) | |
| log.Info("Done linking drivers") | |
| if err != nil { | |
| return fmt.Errorf("%w: %v", errInstallerFailed, err) | |
| } | |
| return nil | |
| } | |
| func installUserLibs(nvidiaDir, arch string) error { | |
| log.Info("Installing userspace libraries...") | |
| cmdArgs := []string{ | |
| "--utility-prefix=" + gpuInstallDirContainer, | |
| "--opengl-prefix=" + gpuInstallDirContainer, | |
| "--x-prefix=" + gpuInstallDirContainer, | |
| "--install-libglvnd", | |
| "--log-file-name=" + filepath.Join(gpuInstallDirContainer, "nvidia-installer.log"), | |
| "--silent", | |
| "--accept-license", | |
| "--no-kernel-module", | |
| } | |
| // Arm64 installer does not recognize the 32 bit compatibility libraries command line option. | |
| if arch == "x86_64" { | |
| cmdArgs = append(cmdArgs, "--no-install-compat32-libs") | |
| } | |
| cmd := exec.Command(filepath.Join(nvidiaDir, "nvidia-installer"), cmdArgs...) | |
| cmd.Env = append(cmd.Env, "PATH="+filepath.Join(gpuInstallDirContainer, "bin")+":"+os.Getenv("PATH")) | |
| log.Infof("Installer arguments:\n%v", cmd.Args) | |
| if err := utils.RunCommandAndLogOutput(cmd, false); err != nil { | |
| return fmt.Errorf("failed to run GPU driver installer: %v", err) | |
| } | |
| // Copy the libstdc++.so.* files from the host to the container - needed for nvidia-gridd to run | |
| searchDirs := []string{ | |
| "/usr/lib/x86_64-linux-gnu", | |
| "/usr/lib64", | |
| "/usr/lib", | |
| "/lib/x86_64-linux-gnu", | |
| "/lib64", | |
| } | |
| var copied bool | |
| for _, dir := range searchDirs { | |
| matches, err := filepath.Glob(filepath.Join(dir, "libstdc++.so.*")) | |
| if err != nil || len(matches) == 0 { | |
| continue | |
| } | |
| // To safely handle cases where multiple major versions exist (e.g. .so.5 and .so.6), | |
| // we iterate through the matches and copy any file representing a major version. | |
| dstDir := filepath.Join(gpuInstallDirContainer, "gridd-libs") | |
| if err := os.MkdirAll(dstDir, defaultFilePermission); err != nil { | |
| log.Warningf("Failed to create directory %s: %v", dstDir, err) | |
| continue | |
| } | |
| for _, match := range matches { | |
| dstLib := filepath.Join(dstDir, filepath.Base(match)) | |
| if err := utils.CopyFile(match, dstLib); err == nil { | |
| os.Chmod(dstLib, 0755) | |
| log.Infof("Successfully copied %s to %s", match, dstLib) | |
| copied = true | |
| } else { | |
| log.Warningf("Failed copy %s to %s: %v", match, dstLib, err) | |
| } | |
| } | |
| // Once the file was copied from one of the valid standard paths, break. | |
| if copied { | |
| break | |
| } | |
| } | |
| if !copied { | |
| log.Warningf("Failed to find or copy any major version of libstdc++.so.* in the search paths.") | |
| } | |
| log.Info("Done installing userspace libraries") | |
| return nil | |
| } | |
| // RunDriverInstaller runs GPU driver installer. Only works if the provided | |
| // installer includes precompiled drivers. | |
| func RunDriverInstaller(toolchainDir, installerFilename, driverVersion, arch, kernelDriversPath string, needSigned, test, legacyLink, noVerify bool, moduleParameters modules.ModuleParameters) error { | |
| log.Info("Running GPU driver installer") | |
| // Extract files to a fixed path first to make sure md5sum of generated gpu drivers are consistent. | |
| extractDir := "/tmp/extract" | |
| if err := os.RemoveAll(extractDir); err != nil { | |
| return fmt.Errorf("failed to clean %q: %v", extractDir, err) | |
| } | |
| cmd := exec.Command("sh", installerFilename, "-x", "--target", extractDir) | |
| cmd.Dir = gpuInstallDirContainer | |
| if err := cmd.Run(); err != nil { | |
| return errors.Wrap(err, "failed to extract installer files") | |
| } | |
| // Extract precompiled artifacts. | |
| if err := extractPrecompiled(extractDir); err != nil { | |
| return fmt.Errorf("failed to extract precompiled artifacts: %v", err) | |
| } | |
| // Link drivers. | |
| var legacyInstallerFailed bool | |
| if legacyLink { | |
| if err := linkDriversLegacy(toolchainDir, extractDir); err != nil { | |
| if stderrors.Is(err, errInstallerFailed) { | |
| // This case is expected when module signature enforcement is enabled. | |
| // Since the installer terminated early, we need to re-run it after | |
| // signing modules. | |
| // | |
| // If we don't sign modules (i.e. needSigned is false), then we'll see | |
| // an error when we load the modules, and that will be fatal. | |
| legacyInstallerFailed = true | |
| } else { | |
| return fmt.Errorf("failed to link drivers: %v", err) | |
| } | |
| } | |
| } else { | |
| if err := linkDrivers(toolchainDir, extractDir); err != nil { | |
| return fmt.Errorf("failed to link drivers: %v", err) | |
| } | |
| } | |
| kernelFiles, err := ioutil.ReadDir(filepath.Join(extractDir, "kernel")) | |
| if err != nil { | |
| return errors.Wrapf(err, "failed to list files in directory %s", filepath.Join(extractDir, "kernel")) | |
| } | |
| if needSigned { | |
| // sign GPU drivers. | |
| for _, kernelFile := range kernelFiles { | |
| if strings.HasSuffix(kernelFile.Name(), ".ko") { | |
| module := kernelFile.Name() | |
| signaturePath := signing.GetModuleSignature(module) | |
| modulePath := filepath.Join(extractDir, "kernel", module) | |
| signedModulePath := filepath.Join(gpuInstallDirContainer, "drivers", module) | |
| if err := modules.AppendSignature(signedModulePath, modulePath, signaturePath); err != nil { | |
| return errors.Wrapf(err, "failed to sign kernel module %s", module) | |
| } | |
| } | |
| } | |
| } else if !legacyLink { | |
| // Copy drivers to the desired end directory. This is done as part of | |
| // `modules.AppendSignature` in the above signing block, but we need to do | |
| // it for unsigned modules as well. Legacy linking already does this copy | |
| // in the unsigned case (we expect that legacy linking also does this when | |
| // the installer fails); we skip this block in the legacy link case to avoid | |
| // redundancy. | |
| for _, kernelFile := range kernelFiles { | |
| if strings.HasSuffix(kernelFile.Name(), ".ko") { | |
| module := kernelFile.Name() | |
| src := filepath.Join(extractDir, "kernel", module) | |
| dst := filepath.Join(gpuInstallDirContainer, "drivers", module) | |
| if err := utils.CopyFile(src, dst); err != nil { | |
| return fmt.Errorf("failed to copy kernel module %q: %v", module, err) | |
| } | |
| } | |
| } | |
| } | |
| // Load GPU drivers. | |
| // The legacy linking method does this when the installer doesn't fail (i.e. | |
| // module signature verification isn't enforced). | |
| if (legacyLink && legacyInstallerFailed) || !legacyLink { | |
| if err := loadGPUDrivers(moduleParameters, test, false, noVerify, kernelDriversPath); err != nil { | |
| return fmt.Errorf("%w: %v", ErrDriverLoad, err) | |
| } | |
| } | |
| // Install libs. | |
| // The legacy linking method does this when the installer doesn't fail (i.e. | |
| // module signature verification isn't enforced). | |
| if (legacyLink && legacyInstallerFailed) || !legacyLink { | |
| if err := installUserLibs(extractDir, arch); err != nil { | |
| return fmt.Errorf("failed to install userspace libraries: %v", err) | |
| } | |
| // Driver version may be empty if custom nvidia-installer-url is used | |
| // read from manifest file | |
| if driverVersion == "" { | |
| driverVersion = findDriverVersionManifestFile(filepath.Join(extractDir, ".manifest")) | |
| log.Info("found driver version from nvidia-installer pkg ", driverVersion) | |
| } | |
| if err := prepareGSPFirmware(extractDir, driverVersion, needSigned); err != nil { | |
| return fmt.Errorf("failed to prepare GSP firmware, err: %v", err) | |
| } | |
| } | |
| return nil | |
| } | |
| // findDriverVersionManifestFile tries to read .manifest file to find driverVersion present in the manifest. | |
| func findDriverVersionManifestFile(manifestFilePath string) string { | |
| manifestFileRawBytes, err := os.ReadFile(manifestFilePath) | |
| if err != nil { | |
| return "" | |
| } | |
| lines := strings.Split(string(manifestFileRawBytes), "\n") | |
| if len(lines) < 2 { | |
| return "" | |
| } | |
| // driver version present in the second line of the file | |
| driverVersion := strings.TrimSpace(lines[1]) | |
| return driverVersion | |
| } |