|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + "github.com/spf13/cobra" |
| 7 | + "sub-store-manager-cli/docker" |
| 8 | + "sub-store-manager-cli/lib" |
| 9 | + "sub-store-manager-cli/vars" |
| 10 | +) |
| 11 | + |
| 12 | +var updateCmd = &cobra.Command{ |
| 13 | + Use: "update", |
| 14 | + Short: "update a sub-store docker container", |
| 15 | + Run: func(cmd *cobra.Command, args []string) { |
| 16 | + updateContainer() |
| 17 | + }, |
| 18 | +} |
| 19 | + |
| 20 | +func init() { |
| 21 | + updateCmd.Flags().StringVarP(&inputVersion, "version", "v", "", "The target version to update") |
| 22 | + updateCmd.Flags().StringVarP(&inputName, "name", "n", "", "The target sub-store container name to update") |
| 23 | +} |
| 24 | + |
| 25 | +func updateContainer() { |
| 26 | + name := inputName |
| 27 | + if name == "" { |
| 28 | + name = vars.DockerNameBE |
| 29 | + } |
| 30 | + |
| 31 | + oldContainer, isExist := docker.GetContainerByName(name) |
| 32 | + if !isExist { |
| 33 | + lib.PrintError("The container does not exist.", nil) |
| 34 | + } |
| 35 | + |
| 36 | + c := docker.Container{ |
| 37 | + Name: inputName, |
| 38 | + ImageName: oldContainer.ImageName, |
| 39 | + ContainerType: oldContainer.ContainerType, |
| 40 | + HostPort: oldContainer.HostPort, |
| 41 | + Version: inputVersion, |
| 42 | + } |
| 43 | + |
| 44 | + // 检查指定版本 |
| 45 | + if inputVersion == "" { |
| 46 | + c.SetLatestVersion() |
| 47 | + fmt.Println("No version specified, using the latest version") |
| 48 | + } else { |
| 49 | + if c.ContainerType == vars.ContainerTypeFE { |
| 50 | + c.SetLatestVersion() |
| 51 | + lib.PrintInfo("The version flag is ignored when target is a front-end container.") |
| 52 | + } else { |
| 53 | + isValid := c.CheckVersionValid() |
| 54 | + if !isValid { |
| 55 | + lib.PrintError("The version is not valid.", nil) |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // 如果当前运行的版本就是目标版本,则不更新 |
| 61 | + if oldContainer.Version == c.Version { |
| 62 | + lib.PrintInfo("The current version is the target version, no need to update.") |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + // 获取旧容器的端口信息 |
| 67 | + if p, err := oldContainer.GetPortInfo(); err != nil { |
| 68 | + lib.PrintError("Failed to get port info:", err) |
| 69 | + } else { |
| 70 | + c.HostPort = p.Public |
| 71 | + } |
| 72 | + |
| 73 | + c.SetDockerfile("") |
| 74 | + c.CreateImage() |
| 75 | + |
| 76 | + // 删除旧容器, 启动新容器 |
| 77 | + oldContainer.Stop() |
| 78 | + oldContainer.Delete() |
| 79 | + c.StartImage() |
| 80 | +} |
0 commit comments