From 230d04dd751a780e49712de302b48c0ed1beb6fe Mon Sep 17 00:00:00 2001 From: ssongliu <73214554+ssongliu@users.noreply.github.com> Date: Tue, 12 Dec 2023 15:34:08 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=BC=96=E6=8E=92=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=A4=B1=E8=B4=A5=E5=9B=9E=E6=BB=9A=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=20(#3288)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #3277 --- backend/app/service/container_compose.go | 29 +++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/backend/app/service/container_compose.go b/backend/app/service/container_compose.go index b0d651d4a..9d1e9b891 100644 --- a/backend/app/service/container_compose.go +++ b/backend/app/service/container_compose.go @@ -216,7 +216,8 @@ func (u *ContainerService) ComposeUpdate(req dto.ComposeUpdate) error { if cmd.CheckIllegal(req.Name, req.Path) { return buserr.New(constant.ErrCmdIllegal) } - if _, err := os.Stat(req.Path); err != nil { + oldFile, err := os.ReadFile(req.Path) + if err != nil { return fmt.Errorf("load file with path %s failed, %v", req.Path, err) } file, err := os.OpenFile(req.Path, os.O_WRONLY|os.O_TRUNC, 0640) @@ -230,10 +231,16 @@ func (u *ContainerService) ComposeUpdate(req dto.ComposeUpdate) error { global.LOG.Infof("docker-compose.yml %s has been replaced, now start to docker-compose restart", req.Path) if stdout, err := compose.Down(req.Path); err != nil { - return errors.New(string(stdout)) + if err := recreateCompose(string(oldFile), req.Path); err != nil { + return fmt.Errorf("update failed when handle compose down, err: %s, recreate failed: %v", string(stdout), err) + } + return fmt.Errorf("update failed when handle compose down, err: %s", string(stdout)) } if stdout, err := compose.Up(req.Path); err != nil { - return errors.New(string(stdout)) + if err := recreateCompose(string(oldFile), req.Path); err != nil { + return fmt.Errorf("update failed when handle compose up, err: %s, recreate failed: %v", string(stdout), err) + } + return fmt.Errorf("update failed when handle compose up, err: %s", string(stdout)) } return nil @@ -261,3 +268,19 @@ func (u *ContainerService) loadPath(req *dto.ComposeCreate) error { } return nil } + +func recreateCompose(content, path string) error { + file, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0640) + if err != nil { + return err + } + defer file.Close() + write := bufio.NewWriter(file) + _, _ = write.WriteString(content) + write.Flush() + + if stdout, err := compose.Up(path); err != nil { + return errors.New(string(stdout)) + } + return nil +}