1
0

onlineStatus.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package loadbalance
  2. import (
  3. "strconv"
  4. "strings"
  5. "time"
  6. )
  7. // Return if the target host is online
  8. func (m *RouteManager) IsTargetOnline(upstreamIP string) bool {
  9. value, ok := m.OnlineStatus.Load(upstreamIP)
  10. if !ok {
  11. // Assume online if not found, also update the map
  12. m.OnlineStatus.Store(upstreamIP, true)
  13. return true
  14. }
  15. isOnline, ok := value.(bool)
  16. return ok && isOnline
  17. }
  18. // Notify the host online state, should be called from uptime monitor
  19. func (m *RouteManager) NotifyHostOnlineState(upstreamIP string, isOnline bool) {
  20. //if the upstream IP contains http or https, strip it
  21. upstreamIP = strings.TrimPrefix(upstreamIP, "http://")
  22. upstreamIP = strings.TrimPrefix(upstreamIP, "https://")
  23. //Check previous state and update
  24. if m.IsTargetOnline(upstreamIP) == isOnline {
  25. return
  26. }
  27. m.OnlineStatus.Store(upstreamIP, isOnline)
  28. m.println("Updating upstream "+upstreamIP+" online state to "+strconv.FormatBool(isOnline), nil)
  29. }
  30. // Set this host unreachable for a given amount of time defined in timeout
  31. // this shall be used in passive fallback. The uptime monitor should call to NotifyHostOnlineState() instead
  32. func (m *RouteManager) NotifyHostUnreachableWithTimeout(upstreamIp string, timeout int64) {
  33. //if the upstream IP contains http or https, strip it
  34. upstreamIp = strings.TrimPrefix(upstreamIp, "http://")
  35. upstreamIp = strings.TrimPrefix(upstreamIp, "https://")
  36. if timeout <= 0 {
  37. //Set to the default timeout
  38. timeout = 60
  39. }
  40. if !m.IsTargetOnline(upstreamIp) {
  41. //Already offline
  42. return
  43. }
  44. m.OnlineStatus.Store(upstreamIp, false)
  45. m.println("Setting upstream "+upstreamIp+" unreachable for "+strconv.FormatInt(timeout, 10)+"s", nil)
  46. go func() {
  47. //Set the upstream back to online after the timeout
  48. <-time.After(time.Duration(timeout) * time.Second)
  49. m.NotifyHostOnlineState(upstreamIp, true)
  50. }()
  51. }
  52. // FilterOfflineOrigins return only online origins from a list of origins
  53. func (m *RouteManager) FilterOfflineOrigins(origins []*Upstream) []*Upstream {
  54. var onlineOrigins []*Upstream
  55. for _, origin := range origins {
  56. if m.IsTargetOnline(origin.OriginIpOrDomain) {
  57. onlineOrigins = append(onlineOrigins, origin)
  58. }
  59. }
  60. return onlineOrigins
  61. }