docker_utils.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package main
  2. import (
  3. "fmt"
  4. "os/exec"
  5. "strings"
  6. "testing"
  7. )
  8. func deleteContainer(container string) error {
  9. container = strings.Replace(container, "\n", " ", -1)
  10. container = strings.Trim(container, " ")
  11. rmArgs := fmt.Sprintf("rm %v", container)
  12. rmSplitArgs := strings.Split(rmArgs, " ")
  13. rmCmd := exec.Command(dockerBinary, rmSplitArgs...)
  14. exitCode, err := runCommand(rmCmd)
  15. // set error manually if not set
  16. if exitCode != 0 && err == nil {
  17. err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
  18. }
  19. return err
  20. }
  21. func getAllContainers() (string, error) {
  22. getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
  23. out, exitCode, err := runCommandWithOutput(getContainersCmd)
  24. if exitCode != 0 && err == nil {
  25. err = fmt.Errorf("failed to get a list of containers: %v\n", out)
  26. }
  27. return out, err
  28. }
  29. func deleteAllContainers() error {
  30. containers, err := getAllContainers()
  31. if err != nil {
  32. fmt.Println(containers)
  33. return err
  34. }
  35. if err = deleteContainer(containers); err != nil {
  36. return err
  37. }
  38. return nil
  39. }
  40. func deleteImages(images string) error {
  41. rmiCmd := exec.Command(dockerBinary, "rmi", images)
  42. exitCode, err := runCommand(rmiCmd)
  43. // set error manually if not set
  44. if exitCode != 0 && err == nil {
  45. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  46. }
  47. return err
  48. }
  49. func cmd(t *testing.T, args ...string) (string, int, error) {
  50. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  51. errorOut(err, t, fmt.Sprintf("'%s' failed with errors: %v (%v)", strings.Join(args, " "), err, out))
  52. return out, status, err
  53. }
  54. func findContainerIp(t *testing.T, id string) string {
  55. cmd := exec.Command(dockerBinary, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  56. out, _, err := runCommandWithOutput(cmd)
  57. if err != nil {
  58. t.Fatal(err, out)
  59. }
  60. return strings.Trim(out, " \r\n'")
  61. }