Skip to content

Commit

Permalink
fix: improve mongodump command execution and error handling
Browse files Browse the repository at this point in the history
- Fix typo in comment about printing version number
- Improve error message when failing to get mongodump version
- Remove "mongodump" from initial flags slice
- Move password to environment variable instead of command flag
- Change command execution to use "mongodump" directly instead of through bash
- Add error handling for starting and waiting for the mongodump command

Signed-off-by: Bo-Yi Wu <[email protected]>
  • Loading branch information
appleboy committed Jan 23, 2025
1 parent dd44d09 commit 726c300
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions pkg/dbdump/mongo/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ func getHostPort(h string) (string, string) {
func (d Dump) Exec(ctx context.Context) error {
envs := os.Environ()

// Print the version number fo rht ecommand line tools
// Print the version number for the command line tools
cmd := exec.CommandContext(ctx, "mongodump", "--version")
cmd.Env = envs
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
trace(cmd)
if err := cmd.Run(); err != nil {
return err
return fmt.Errorf("failed to get mongodump version: %w", err)
}

flags := []string{"mongodump"}
flags := []string{}
host, port := getHostPort(d.Host)
if host != "" {
flags = append(flags, "-h", host)
Expand All @@ -57,7 +57,7 @@ func (d Dump) Exec(ctx context.Context) error {
}

if d.Password != "" {
flags = append(flags, "-p", d.Password)
envs = append(envs, "MONGO_PWD="+d.Password)
}

if d.Name != "" {
Expand All @@ -73,12 +73,20 @@ func (d Dump) Exec(ctx context.Context) error {
flags = append(flags, d.Opts)
}

cmd = exec.CommandContext(ctx, "bash", "-c", strings.Join(flags, " ")) //nolint:gosec
cmd = exec.CommandContext(ctx, "mongodump", flags...)
cmd.Env = envs
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
trace(cmd)
return cmd.Run()
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start mongodump: %w", err)
}

if err := cmd.Wait(); err != nil {
return fmt.Errorf("mongodump failed: %w", err)
}

return nil
}

// trace prints the command to the stdout.
Expand Down

0 comments on commit 726c300

Please sign in to comment.