main-old.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/docker/docker/api/types"
  6. "github.com/docker/docker/client"
  7. "sync"
  8. "time"
  9. )
  10. // var counter int
  11. var lock sync.Mutex
  12. /*
  13. {
  14. "<patp>":{
  15. "status":<container-status>
  16. }
  17. }
  18. */
  19. var urbitBroadcast = make(map[string]map[string]string)
  20. func broadcast() {
  21. for {
  22. fmt.Println(urbitBroadcast) // send to websocket as json blob
  23. time.Sleep(250 * time.Millisecond)
  24. }
  25. }
  26. // Example
  27. func getStatus(i int, patp string) {
  28. for {
  29. // Locking the shared state
  30. lock.Lock()
  31. // Create submap
  32. _, exist := urbitBroadcast[patp]
  33. if !exist {
  34. urbitBroadcast[patp] = make(map[string]string)
  35. }
  36. //Get container running status
  37. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  38. if err != nil {
  39. //panic(err)
  40. fmt.Println(err)
  41. } else {
  42. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
  43. if err != nil {
  44. urbitBroadcast[patp]["status"] = "error"
  45. } else {
  46. for _, container := range containers {
  47. for _, name := range container.Names {
  48. fasPatp := "/" + patp
  49. if name == fasPatp {
  50. urbitBroadcast[patp]["status"] = container.Status
  51. }
  52. }
  53. }
  54. }
  55. }
  56. // Unlocking the shared state
  57. lock.Unlock()
  58. // Arbitary sleep
  59. time.Sleep(5 * time.Second)
  60. }
  61. }
  62. func main() {
  63. /*
  64. Temporary Hardcode -- from config file
  65. */
  66. piers := []string{"widwet-mornev-nallux-dozryl",
  67. "hocfur-wicnym-nallux-dozryl",
  68. "pinlyd-mattyd-nallux-dozryl",
  69. "solnys-dibmyn-nallux-dozryl",
  70. "wormun-fadwyl-nallux-dozryl",
  71. "nopmul-pollyt",
  72. "nalruc-nallux-dozryl",
  73. }
  74. go broadcast()
  75. for i, patp := range piers {
  76. go getStatus(i, patp)
  77. }
  78. // Waiting for the goroutines to complete
  79. var input string
  80. fmt.Scanln(&input)
  81. }