1
0

docker.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "net/http"
  7. "os"
  8. "os/exec"
  9. "strings"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/client"
  13. "imuslab.com/zoraxy/mod/utils"
  14. )
  15. // IsDockerized checks if the program is running in a Docker container.
  16. func IsDockerized() bool {
  17. // Check for the /proc/1/cgroup file
  18. file, err := os.Open("/proc/1/cgroup")
  19. if err != nil {
  20. return false
  21. }
  22. defer file.Close()
  23. scanner := bufio.NewScanner(file)
  24. for scanner.Scan() {
  25. if strings.Contains(scanner.Text(), "docker") {
  26. return true
  27. }
  28. }
  29. return false
  30. }
  31. // IsDockerInstalled checks if Docker is installed on the host.
  32. func IsDockerInstalled() bool {
  33. _, err := exec.LookPath("docker")
  34. return err == nil
  35. }
  36. // HandleDockerAvaible check if teh docker related functions should be avaible in front-end
  37. func HandleDockerAvailable(w http.ResponseWriter, r *http.Request) {
  38. dockerAvailable := IsDockerized()
  39. js, _ := json.Marshal(dockerAvailable)
  40. utils.SendJSONResponse(w, string(js))
  41. }
  42. // handleDockerContainersList return the current list of docker containers
  43. // currently listening to the same bridge network interface. See PR #202 for details.
  44. func HandleDockerContainersList(w http.ResponseWriter, r *http.Request) {
  45. apiClient, err := client.NewClientWithOpts(client.WithVersion("1.43"))
  46. if err != nil {
  47. utils.SendErrorResponse(w, err.Error())
  48. return
  49. }
  50. defer apiClient.Close()
  51. containers, err := apiClient.ContainerList(context.Background(), container.ListOptions{All: true})
  52. if err != nil {
  53. utils.SendErrorResponse(w, err.Error())
  54. return
  55. }
  56. networks, err := apiClient.NetworkList(context.Background(), types.NetworkListOptions{})
  57. if err != nil {
  58. utils.SendErrorResponse(w, err.Error())
  59. return
  60. }
  61. result := map[string]interface{}{
  62. "network": networks,
  63. "containers": containers,
  64. }
  65. js, err := json.Marshal(result)
  66. if err != nil {
  67. utils.SendErrorResponse(w, err.Error())
  68. return
  69. }
  70. utils.SendJSONResponse(w, string(js))
  71. }