main.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package main
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/base64"
  6. "encoding/json"
  7. "flag"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "os"
  12. "strings"
  13. "github.com/containerd/log"
  14. "github.com/docker/docker/libnetwork"
  15. "github.com/docker/docker/libnetwork/diagnostic"
  16. "github.com/docker/docker/libnetwork/drivers/overlay"
  17. )
  18. const (
  19. readyPath = "http://%s:%d/ready"
  20. joinNetwork = "http://%s:%d/joinnetwork?nid=%s"
  21. leaveNetwork = "http://%s:%d/leavenetwork?nid=%s"
  22. clusterPeers = "http://%s:%d/clusterpeers?json"
  23. networkPeers = "http://%s:%d/networkpeers?nid=%s&json"
  24. dumpTable = "http://%s:%d/gettable?nid=%s&tname=%s&json"
  25. deleteEntry = "http://%s:%d/deleteentry?nid=%s&tname=%s&key=%s&json"
  26. )
  27. func httpIsOk(body io.ReadCloser) {
  28. b, err := io.ReadAll(body)
  29. if err != nil {
  30. log.G(context.TODO()).Fatalf("Failed the body parse %s", err)
  31. }
  32. if !strings.Contains(string(b), "OK") {
  33. log.G(context.TODO()).Fatalf("Server not ready %s", b)
  34. }
  35. body.Close()
  36. }
  37. func main() {
  38. ipPtr := flag.String("ip", "127.0.0.1", "ip address")
  39. portPtr := flag.Int("port", 2000, "port")
  40. networkPtr := flag.String("net", "", "target network")
  41. tablePtr := flag.String("t", "", "table to process <sd/overlay>")
  42. remediatePtr := flag.Bool("r", false, "perform remediation deleting orphan entries")
  43. joinPtr := flag.Bool("a", false, "join/leave network")
  44. verbosePtr := flag.Bool("v", false, "verbose output")
  45. flag.Parse()
  46. if *verbosePtr {
  47. _ = log.SetLevel("debug")
  48. }
  49. if _, ok := os.LookupEnv("DIND_CLIENT"); !ok && *joinPtr {
  50. log.G(context.TODO()).Fatal("you are not using the client in docker in docker mode, the use of the -a flag can be disruptive, " +
  51. "please remove it (doc:https://github.com/docker/docker/libnetwork/blob/master/cmd/diagnostic/README.md)")
  52. }
  53. log.G(context.TODO()).Infof("Connecting to %s:%d checking ready", *ipPtr, *portPtr)
  54. resp, err := http.Get(fmt.Sprintf(readyPath, *ipPtr, *portPtr))
  55. if err != nil {
  56. log.G(context.TODO()).WithError(err).Fatalf("The connection failed")
  57. }
  58. httpIsOk(resp.Body)
  59. clusterPeers := fetchNodePeers(*ipPtr, *portPtr, "")
  60. var networkPeers map[string]string
  61. var joinedNetwork bool
  62. if *networkPtr != "" {
  63. if *joinPtr {
  64. log.G(context.TODO()).Infof("Joining the network:%q", *networkPtr)
  65. resp, err = http.Get(fmt.Sprintf(joinNetwork, *ipPtr, *portPtr, *networkPtr))
  66. if err != nil {
  67. log.G(context.TODO()).WithError(err).Fatalf("Failed joining the network")
  68. }
  69. httpIsOk(resp.Body)
  70. joinedNetwork = true
  71. }
  72. networkPeers = fetchNodePeers(*ipPtr, *portPtr, *networkPtr)
  73. if len(networkPeers) == 0 {
  74. log.G(context.TODO()).Warnf("There is no peer on network %q, check the network ID, and verify that is the non truncated version", *networkPtr)
  75. }
  76. }
  77. switch *tablePtr {
  78. case "sd":
  79. fetchTable(*ipPtr, *portPtr, *networkPtr, "endpoint_table", clusterPeers, networkPeers, *remediatePtr)
  80. case "overlay":
  81. fetchTable(*ipPtr, *portPtr, *networkPtr, "overlay_peer_table", clusterPeers, networkPeers, *remediatePtr)
  82. }
  83. if joinedNetwork {
  84. log.G(context.TODO()).Infof("Leaving the network:%q", *networkPtr)
  85. resp, err = http.Get(fmt.Sprintf(leaveNetwork, *ipPtr, *portPtr, *networkPtr))
  86. if err != nil {
  87. log.G(context.TODO()).WithError(err).Fatalf("Failed leaving the network")
  88. }
  89. httpIsOk(resp.Body)
  90. }
  91. }
  92. func fetchNodePeers(ip string, port int, network string) map[string]string {
  93. if network == "" {
  94. log.G(context.TODO()).Infof("Fetch cluster peers")
  95. } else {
  96. log.G(context.TODO()).Infof("Fetch peers network:%q", network)
  97. }
  98. var path string
  99. if network != "" {
  100. path = fmt.Sprintf(networkPeers, ip, port, network)
  101. } else {
  102. path = fmt.Sprintf(clusterPeers, ip, port)
  103. }
  104. resp, err := http.Get(path) //nolint:gosec // G107: Potential HTTP request made with variable url
  105. if err != nil {
  106. log.G(context.TODO()).WithError(err).Fatalf("Failed fetching path")
  107. }
  108. defer resp.Body.Close()
  109. body, err := io.ReadAll(resp.Body)
  110. if err != nil {
  111. log.G(context.TODO()).WithError(err).Fatalf("Failed the body parse")
  112. }
  113. output := diagnostic.HTTPResult{Details: &diagnostic.TablePeersResult{}}
  114. err = json.Unmarshal(body, &output)
  115. if err != nil {
  116. log.G(context.TODO()).WithError(err).Fatalf("Failed the json unmarshalling")
  117. }
  118. log.G(context.TODO()).Debugf("Parsing JSON response")
  119. result := make(map[string]string, output.Details.(*diagnostic.TablePeersResult).Length)
  120. for _, v := range output.Details.(*diagnostic.TablePeersResult).Elements {
  121. log.G(context.TODO()).Debugf("name:%s ip:%s", v.Name, v.IP)
  122. result[v.Name] = v.IP
  123. }
  124. return result
  125. }
  126. func fetchTable(ip string, port int, network, tableName string, clusterPeers, networkPeers map[string]string, remediate bool) {
  127. log.G(context.TODO()).Infof("Fetch %s table and check owners", tableName)
  128. resp, err := http.Get(fmt.Sprintf(dumpTable, ip, port, network, tableName))
  129. if err != nil {
  130. log.G(context.TODO()).WithError(err).Fatalf("Failed fetching endpoint table")
  131. }
  132. defer resp.Body.Close()
  133. body, err := io.ReadAll(resp.Body)
  134. if err != nil {
  135. log.G(context.TODO()).WithError(err).Fatalf("Failed the body parse")
  136. }
  137. output := diagnostic.HTTPResult{Details: &diagnostic.TableEndpointsResult{}}
  138. err = json.Unmarshal(body, &output)
  139. if err != nil {
  140. log.G(context.TODO()).WithError(err).Fatalf("Failed the json unmarshalling")
  141. }
  142. log.G(context.TODO()).Debug("Parsing data structures")
  143. var orphanKeys []string
  144. for _, v := range output.Details.(*diagnostic.TableEndpointsResult).Elements {
  145. decoded, err := base64.StdEncoding.DecodeString(v.Value)
  146. if err != nil {
  147. log.G(context.TODO()).WithError(err).Errorf("Failed decoding entry")
  148. continue
  149. }
  150. switch tableName {
  151. case "endpoint_table":
  152. var elem libnetwork.EndpointRecord
  153. elem.Unmarshal(decoded)
  154. log.G(context.TODO()).Debugf("key:%s value:%+v owner:%s", v.Key, elem, v.Owner)
  155. case "overlay_peer_table":
  156. var elem overlay.PeerRecord
  157. elem.Unmarshal(decoded)
  158. log.G(context.TODO()).Debugf("key:%s value:%+v owner:%s", v.Key, elem, v.Owner)
  159. }
  160. if _, ok := networkPeers[v.Owner]; !ok {
  161. log.G(context.TODO()).Warnf("The element with key:%s does not belong to any node on this network", v.Key)
  162. orphanKeys = append(orphanKeys, v.Key)
  163. }
  164. if _, ok := clusterPeers[v.Owner]; !ok {
  165. log.G(context.TODO()).Warnf("The element with key:%s does not belong to any node on this cluster", v.Key)
  166. }
  167. }
  168. if len(orphanKeys) > 0 && remediate {
  169. log.G(context.TODO()).Warnf("The following keys:%v results as orphan, do you want to proceed with the deletion (this operation is irreversible)? [Yes/No]", orphanKeys)
  170. reader := bufio.NewReader(os.Stdin)
  171. text, _ := reader.ReadString('\n')
  172. text = strings.ReplaceAll(text, "\n", "")
  173. if strings.Compare(text, "Yes") == 0 {
  174. for _, k := range orphanKeys {
  175. resp, err := http.Get(fmt.Sprintf(deleteEntry, ip, port, network, tableName, k))
  176. if err != nil {
  177. log.G(context.TODO()).WithError(err).Errorf("Failed deleting entry k:%s", k)
  178. break
  179. }
  180. resp.Body.Close()
  181. }
  182. } else {
  183. log.G(context.TODO()).Infof("Deletion skipped")
  184. }
  185. }
  186. }