fix(stack): unable to delete invalid stack [EE-5753] (#11813)

This commit is contained in:
Oscar Zhou
2024-06-04 11:34:02 +12:00
committed by GitHub
parent 9c70a43ac3
commit 4a7f96caf6
5 changed files with 48 additions and 18 deletions

View File

@@ -76,15 +76,9 @@ func (manager *ComposeStackManager) Down(ctx context.Context, stack *portainer.S
defer proxy.Close()
}
envFilePath, err := createEnvFile(stack)
if err != nil {
return errors.Wrap(err, "failed to create env file")
}
err = manager.deployer.Remove(ctx, stack.Name, nil, libstack.Options{
WorkingDir: stack.ProjectPath,
EnvFilePath: envFilePath,
Host: url,
WorkingDir: "",
Host: url,
})
return errors.Wrap(err, "failed to remove a stack")
@@ -148,28 +142,46 @@ func createEnvFile(stack *portainer.Stack) (string, error) {
}
defer envfile.Close()
copyDefaultEnvFile(stack, envfile)
// Copy from default .env file
defaultEnvPath := path.Join(stack.ProjectPath, path.Dir(stack.EntryPoint), ".env")
if err = copyDefaultEnvFile(envfile, defaultEnvPath); err != nil {
return "", err
}
for _, v := range stack.Env {
envfile.WriteString(fmt.Sprintf("%s=%s\n", v.Name, v.Value))
// Copy from stack env vars
if err = copyConfigEnvVars(envfile, stack.Env); err != nil {
return "", err
}
return "stack.env", nil
}
// copyDefaultEnvFile copies the default .env file if it exists to the provided writer
func copyDefaultEnvFile(stack *portainer.Stack, w io.Writer) {
defaultEnvFile, err := os.Open(path.Join(path.Join(stack.ProjectPath, path.Dir(stack.EntryPoint)), ".env"))
func copyDefaultEnvFile(w io.Writer, defaultEnvFilePath string) error {
defaultEnvFile, err := os.Open(defaultEnvFilePath)
if err != nil {
// If cannot open a default file, then don't need to copy it.
// We could as well stat it and check if it exists, but this is more efficient.
return
return nil
}
defer defaultEnvFile.Close()
if _, err = io.Copy(w, defaultEnvFile); err == nil {
io.WriteString(w, "\n")
if _, err = fmt.Fprintf(w, "\n"); err != nil {
return fmt.Errorf("failed to copy default env file: %w", err)
}
}
return nil
// If couldn't copy the .env file, then ignore the error and try to continue
}
// copyConfigEnvVars write the environment variables from stack configuration to the writer
func copyConfigEnvVars(w io.Writer, envs []portainer.Pair) error {
for _, v := range envs {
if _, err := fmt.Fprintf(w, "%s=%s\n", v.Name, v.Value); err != nil {
return fmt.Errorf("failed to copy config env vars: %w", err)
}
}
return nil
}