Enhance Docker Installation and Management Commands

- Improved Docker installation process for Ubuntu systems
- Added support for dynamic Docker version detection
- Enhanced Docker local and online installation commands
- Implemented more robust Docker removal functionality
- Updated Docker installation to use system-specific package sources
- Added better error handling and logging for Docker operations
- Refined Docker service startup and configuration checks
This commit is contained in:
zeaslity
2025-02-28 17:45:12 +08:00
parent bffb643a56
commit 5c39bd7594
16 changed files with 586 additions and 86 deletions

View File

@@ -8,6 +8,7 @@ import (
"agent-wdd/utils"
"fmt"
"runtime"
"strings"
"github.com/spf13/cobra"
)
@@ -282,8 +283,14 @@ func addSSHSubcommands(sshCmd *cobra.Command) {
port := "22333"
log.Info("[ModifySSHPort] modify ssh port to: %s", port)
// 修改ssh端口
utils.AppendContentToFile(fmt.Sprintf("Port %s", port), "/etc/ssh/sshd_config")
// 文件中已经包含了Port 22333 则pass
sshdPortString := fmt.Sprintf("Port %s", port)
if utils.FindContentInFile(sshdPortString, "/etc/ssh/sshd_config") {
log.Info("[ModifySSHPort] ssh port already modified to: %s", port)
} else {
// 修改ssh端口
utils.AppendContentToFile(sshdPortString, "/etc/ssh/sshd_config")
}
// 重启ssh服务
ok, resultLog := op.SystemdRestart("sshd")
@@ -309,7 +316,7 @@ func addSSHSubcommands(sshCmd *cobra.Command) {
}
// 修改ssh配置
utils.AppendContentToFile(beans.DefaultSshdConfig, "/etc/ssh/sshd_config")
utils.AppendOverwriteContentToFile(beans.DefaultSshdConfig, "/etc/ssh/sshd_config")
// 重启ssh服务
ok, resultLog := op.SystemdRestart("sshd")
@@ -330,8 +337,7 @@ func addSSHSubcommands(sshCmd *cobra.Command) {
func addDockerSubcommands(cmd *cobra.Command) {
onlineCmd := &cobra.Command{
Use: "online [version]",
Short: "网络安装Docker",
Args: cobra.ExactArgs(1),
Short: "网络安装Docker, 如果不指定参数默认安装20.10.15版本",
Run: func(cmd *cobra.Command, args []string) {
// 检查参数
@@ -339,15 +345,124 @@ func addDockerSubcommands(cmd *cobra.Command) {
fmt.Printf("Installing Docker version: %s\n", args[0])
}
// 没有传递参数,使用默认参数
version := "20.10.15"
log.Info("Installing Docker version: %s", version)
// 安装docker
packOperator := op.AgentPackOperator
packOperator.PackageInit()
// ubuntu 和 centos的安装命令是不是一样的
packOperator.Install([]string{"docker-ce", "docker-ce-cli", "containerd.io", "docker-buildx-plugin", "docker-compose-plugin"})
configCache := config.ConfigCache
if configCache.Agent.OS.IsUbuntuType {
// 安装apt-transport-https ca-certificates curl gnupg software-properties-common 依赖部分
packOperator.Install([]string{"apt-transport-https", "ca-certificates", "curl", "gnupg", "software-properties-common"})
// 安装docker的 gpg key
dockerGPGFilePath := "/etc/apt/keyrings/docker.gpg"
dockerAPTFilePath := "/etc/apt/sources.list.d/docker.list"
dockerGPGSource := "https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu/gpg"
dockerAPTSource := "https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu"
// 创建docker的 gpg key 文件
utils.CreateFolder("/etc/apt/keyrings")
// 删除docker的 gpg key 文件
utils.RemoveFile(dockerGPGFilePath)
utils.RemoveFile(dockerAPTFilePath)
// 如果可以访问外网,则使用外网源
if configCache.Agent.Network.Internet == 9 {
dockerGPGSource = "https://download.docker.com/linux/ubuntu/gpg"
dockerAPTSource = "https://download.docker.com/linux/ubuntu"
}
ok, l2 := op.PipeLineCommandExecutor([][]string{
{
"curl",
"-fsSL",
dockerGPGSource,
},
{
"gpg",
"--dearmor",
"-o",
dockerGPGFilePath,
},
})
if !ok {
log.Error("下载docker gpg文件失败: %s", l2)
return
}
if !utils.FileExistAndNotNull(dockerGPGFilePath) {
log.Error("添加gpg失败")
return
}
op.SingleLineCommandExecutor([]string{
"chmod",
"a+r",
dockerGPGFilePath,
},
)
if configCache.Agent.OS.OSReleaseCode == "" {
log.Error("获取系统发行版代号失败! 无法安装docker!")
return
}
dockerAPTSourceCommand := "deb [arch=" + configCache.Agent.OS.Arch + " signed-by=" + dockerGPGFilePath + "] " + dockerAPTSource + " " + configCache.Agent.OS.OSReleaseCode + " stable"
log.Info("dockerAPTSourceCommand is => %s ", dockerAPTSourceCommand)
utils.AppendOverwriteContentToFile(dockerAPTSourceCommand, dockerAPTFilePath)
// 强制初始化APT update
packOperator.PackageInitForce()
// 20.04 default
specificDockerVersion := "5:20.10.24~3-0~ubuntu-" + configCache.Agent.OS.OSReleaseCode
// apt-cache madison docker-ce | grep 20.10.20 | awk '{print$3}'
// get by method
ok, log4 := op.HardCodeCommandExecutor("apt-cache madison docker-ce | grep 20.10.20 | awk '{print$3}'")
if ok && log4 != nil && len(log4) > 0 {
specificDockerVersion = strings.TrimSpace(log4[0])
fmt.Println("get docker version from online => " + specificDockerVersion)
}
log.Info("需要安装的docker版本为 => %s", specificDockerVersion)
dockerStaffList := []string{
"docker-ce=" + specificDockerVersion,
"docker-ce-cli=" + specificDockerVersion,
"containerd.io",
"docker-compose-plugin",
}
ok = packOperator.Install(dockerStaffList)
if !ok {
log.Error("安装docker存在问题请检查!")
return
}
} else {
log.Error("当前系统不是ubuntu系统暂时无法安装docker!")
return
}
log.Info("安装docker成功!")
// 启动docker
op.SystemdUp("docker")
op.SystemdEnable("docker")
// 检查docker是否启动成功
ok, resultLog := op.SystemIsRunning("docker")
if !ok {
log.Error("docker启动失败: %s", resultLog)
return
}
log.Info("docker启动成功! ")
},
}
@@ -357,13 +472,45 @@ func addDockerSubcommands(cmd *cobra.Command) {
Short: "卸载Docker",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Removing Docker...")
// 检查docker是二进制安装还是通过包安装的
dockerExists := op.CommandExistsByPath("docker")
if !dockerExists {
log.Info("Docker 未安装,无需卸载!")
return
}
// 卸载docker
packOperator := op.AgentPackOperator
packOperator.PackageInit()
packOperator.Remove([]string{"docker-ce", "docker-ce-cli", "containerd.io", "docker-buildx-plugin", "docker-compose-plugin"})
// 删除docker目录
utils.RemoveFile("/usr/bin/docker")
utils.RemoveFile("/usr/bin/docker-compose")
utils.RemoveFile("/usr/bin/docker-buildx")
utils.RemoveFile("/usr/bin/docker-compose-plugin")
utils.RemoveFile("/usr/bin/containerd")
// 删除docker的配置文件 systemd
utils.RemoveFile("/etc/systemd/system/docker.service")
utils.RemoveFile("/etc/systemd/system/docker.socket")
utils.RemoveFile("/etc/systemd/system/containerd.service")
utils.RemoveFile(beans.ContainerdServiceFile)
utils.RemoveFile(beans.DockerSocketFile)
utils.RemoveFile(beans.DockerServiceFile)
// 删除docker的日志文件
utils.RemoveFile("/var/log/docker")
log.Info("Docker 卸载成功!")
},
}
localCmd := &cobra.Command{
Use: "local [path]",
Short: "本地安装Docker",
Args: cobra.ExactArgs(1),
Use: "local",
Short: "本地安装Docker, 默认安装20.10.15版本, 安装目录为 " + dockerLocalInstallPath,
Run: func(cmd *cobra.Command, args []string) {
log.Info("Installing Docker from local file: %s", dockerLocalInstallPath)
@@ -385,11 +532,24 @@ func addDockerSubcommands(cmd *cobra.Command) {
}
// 设置权限
chmodCmd := []string{"chmod", "777", "-R", "/usr/bin/docker*"}
ok, resultLog := op.SingleLineCommandExecutor(chmodCmd)
if !ok {
log.Error("Failed to set permissions for Docker binaries: %s", resultLog)
return
dockerBinList := []string{
"docker-init",
"containerd",
"ctr",
"runc",
"dockerd",
"docker-proxy",
"containerd-shim",
"docker",
"containerd-shim-runc-v2",
}
for _, bin := range dockerBinList {
ok, resultLog := op.HardCodeCommandExecutor("chmod 777 /usr/bin/" + bin)
if !ok {
log.Error("Failed to set permissions for Docker binaries: %s", resultLog)
return
}
}
// 配置并启动Docker服务
@@ -408,7 +568,7 @@ func addDockerSubcommands(cmd *cobra.Command) {
}
log.Info("docker dameon file append success !")
ok, resultLog = op.SystemdDaemonReload()
ok, resultLog := op.SystemdDaemonReload()
if !ok {
log.Error("daemon reload error ! %s", resultLog)
return