discovery.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package discovery
  2. import (
  3. "fmt"
  4. "net/http"
  5. "sort"
  6. "time"
  7. )
  8. type Scanner struct {
  9. Host string
  10. ScanRange *[2]int
  11. }
  12. func NewScanner(host string, scanRange *[2]int) *Scanner {
  13. return &Scanner{
  14. Host: host,
  15. ScanRange: scanRange,
  16. }
  17. }
  18. func (s *Scanner) Discover() []int {
  19. ports := findByCmdline()
  20. if len(ports) == 0 {
  21. ports = findByPID()
  22. }
  23. if len(ports) == 0 && s.ScanRange != nil {
  24. ports = scanPorts(s.Host, s.ScanRange[0], s.ScanRange[1])
  25. }
  26. return unique(ports)
  27. }
  28. func scanPorts(host string, startPort, endPort int) []int {
  29. var found []int
  30. client := http.Client{Timeout: 1 * time.Second}
  31. for port := startPort; port <= endPort; port++ {
  32. resp, err := client.Get(fmt.Sprintf("http://%s:%d/global/health", host, port))
  33. if err == nil && resp.StatusCode == 200 {
  34. found = append(found, port)
  35. resp.Body.Close()
  36. }
  37. }
  38. return found
  39. }
  40. func contains(slice []int, val int) bool {
  41. for _, v := range slice {
  42. if v == val {
  43. return true
  44. }
  45. }
  46. return false
  47. }
  48. func unique(slice []int) []int {
  49. keys := make(map[int]bool)
  50. var result []int
  51. for _, v := range slice {
  52. if !keys[v] {
  53. keys[v] = true
  54. result = append(result, v)
  55. }
  56. }
  57. sort.Ints(result)
  58. return result
  59. }