| 733 | } |
| 734 | |
| 735 | func (e *DockerEnvironment) close() { |
| 736 | if e == nil || e.closed { |
| 737 | return |
| 738 | } |
| 739 | |
| 740 | // Kill the services in the opposite order. |
| 741 | for i := len(e.started) - 1; i >= 0; i-- { |
| 742 | n := e.started[i].Name() |
| 743 | if err := e.started[i].Kill(); err != nil { |
| 744 | e.logger.Log("Unable to kill service", n, ":", err.Error()) |
| 745 | } |
| 746 | } |
| 747 | |
| 748 | // Ensure there are no leftover containers. |
| 749 | if out, err := e.exec( |
| 750 | "docker", |
| 751 | "ps", |
| 752 | "-a", |
| 753 | "--quiet", |
| 754 | "--filter", |
| 755 | fmt.Sprintf("network=%s", e.networkName), |
| 756 | ).CombinedOutput(); err == nil { |
| 757 | for _, containerID := range strings.Split(string(out), "\n") { |
| 758 | containerID = strings.TrimSpace(containerID) |
| 759 | if containerID == "" { |
| 760 | continue |
| 761 | } |
| 762 | |
| 763 | if out, err = e.exec("docker", "rm", "--force", containerID).CombinedOutput(); err != nil { |
| 764 | e.logger.Log(string(out)) |
| 765 | e.logger.Log("Unable to cleanup leftover container", containerID, ":", err.Error()) |
| 766 | } |
| 767 | } |
| 768 | } else { |
| 769 | e.logger.Log(string(out)) |
| 770 | e.logger.Log("Unable to cleanup leftover containers:", err.Error()) |
| 771 | } |
| 772 | |
| 773 | // Teardown the docker network. In case the network does not exists (ie. this function |
| 774 | // is called during the setup of the scenario) we skip the removal in order to not log |
| 775 | // an error which may be misleading. |
| 776 | if ok, err := e.existDockerNetwork(); ok || err != nil { |
| 777 | if out, err := e.exec("docker", "network", "rm", e.networkName).CombinedOutput(); err != nil { |
| 778 | e.logger.Log(string(out)) |
| 779 | e.logger.Log("Unable to remove docker network", e.networkName, ":", err.Error()) |
| 780 | } |
| 781 | } |
| 782 | |
| 783 | if e.dir != "" { |
| 784 | if err := e.exec("chmod", "-R", "777", e.dir).Run(); err != nil { |
| 785 | e.logger.Log("Error while chmod sharedDir", e.dir, "err:", err) |
| 786 | } |
| 787 | if err := os.RemoveAll(e.dir); err != nil { |
| 788 | e.logger.Log("Error while removing sharedDir", e.dir, "err:", err) |
| 789 | } |
| 790 | } |
| 791 | } |