uptime.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. package uptime
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "time"
  7. "imuslab.com/zoraxy/mod/utils"
  8. )
  9. type Record struct {
  10. Timestamp int64
  11. ID string
  12. Name string
  13. URL string
  14. Protocol string
  15. Online bool
  16. StatusCode int
  17. Latency int64
  18. }
  19. type Target struct {
  20. ID string
  21. Name string
  22. URL string
  23. Protocol string
  24. }
  25. type Config struct {
  26. Targets []*Target
  27. Interval int
  28. RecordsInJson int
  29. LogToFile bool
  30. }
  31. type Monitor struct {
  32. Config *Config
  33. OnlineStatusLog map[string][]*Record
  34. }
  35. // Default configs
  36. var exampleTarget = Target{
  37. ID: "example",
  38. Name: "Example",
  39. URL: "example.com",
  40. Protocol: "https",
  41. }
  42. //Create a new uptime monitor
  43. func NewUptimeMonitor(config *Config) (*Monitor, error) {
  44. //Create new monitor object
  45. thisMonitor := Monitor{
  46. Config: config,
  47. OnlineStatusLog: map[string][]*Record{},
  48. }
  49. //Start the endpoint listener
  50. ticker := time.NewTicker(time.Duration(config.Interval) * time.Second)
  51. done := make(chan bool)
  52. //Start the uptime check once first before entering loop
  53. thisMonitor.ExecuteUptimeCheck()
  54. go func() {
  55. for {
  56. select {
  57. case <-done:
  58. return
  59. case t := <-ticker.C:
  60. log.Println("Uptime updated - ", t.Unix())
  61. thisMonitor.ExecuteUptimeCheck()
  62. }
  63. }
  64. }()
  65. return &thisMonitor, nil
  66. }
  67. func (m *Monitor) ExecuteUptimeCheck() {
  68. for _, target := range m.Config.Targets {
  69. //For each target to check online, do the following
  70. var thisRecord Record
  71. if target.Protocol == "http" || target.Protocol == "https" {
  72. online, laterncy, statusCode := getWebsiteStatusWithLatency(target.URL)
  73. thisRecord = Record{
  74. Timestamp: time.Now().Unix(),
  75. ID: target.ID,
  76. Name: target.Name,
  77. URL: target.URL,
  78. Protocol: target.Protocol,
  79. Online: online,
  80. StatusCode: statusCode,
  81. Latency: laterncy,
  82. }
  83. //fmt.Println(thisRecord)
  84. } else {
  85. log.Println("Unknown protocol: " + target.Protocol + ". Skipping")
  86. continue
  87. }
  88. thisRecords, ok := m.OnlineStatusLog[target.ID]
  89. if !ok {
  90. //First record. Create the array
  91. m.OnlineStatusLog[target.ID] = []*Record{&thisRecord}
  92. } else {
  93. //Append to the previous record
  94. thisRecords = append(thisRecords, &thisRecord)
  95. m.OnlineStatusLog[target.ID] = thisRecords
  96. }
  97. }
  98. //TODO: Write results to db
  99. }
  100. func (m *Monitor) AddTargetToMonitor(target *Target) {
  101. // Add target to Config
  102. m.Config.Targets = append(m.Config.Targets, target)
  103. // Add target to OnlineStatusLog
  104. m.OnlineStatusLog[target.ID] = []*Record{}
  105. }
  106. func (m *Monitor) RemoveTargetFromMonitor(targetId string) {
  107. // Remove target from Config
  108. for i, target := range m.Config.Targets {
  109. if target.ID == targetId {
  110. m.Config.Targets = append(m.Config.Targets[:i], m.Config.Targets[i+1:]...)
  111. break
  112. }
  113. }
  114. // Remove target from OnlineStatusLog
  115. delete(m.OnlineStatusLog, targetId)
  116. }
  117. /*
  118. Web Interface Handler
  119. */
  120. func (m *Monitor) HandleUptimeLogRead(w http.ResponseWriter, r *http.Request) {
  121. id, _ := utils.GetPara(r, "id")
  122. if id == "" {
  123. js, _ := json.Marshal(m.OnlineStatusLog)
  124. w.Header().Set("Content-Type", "application/json")
  125. w.Write(js)
  126. } else {
  127. //Check if that id exists
  128. log, ok := m.OnlineStatusLog[id]
  129. if !ok {
  130. http.NotFound(w, r)
  131. return
  132. }
  133. js, _ := json.MarshalIndent(log, "", " ")
  134. w.Header().Set("Content-Type", "application/json")
  135. w.Write(js)
  136. }
  137. }
  138. /*
  139. Utilities
  140. */
  141. // Get website stauts with latency given URL, return is conn succ and its latency and status code
  142. func getWebsiteStatusWithLatency(url string) (bool, int64, int) {
  143. start := time.Now().UnixNano() / int64(time.Millisecond)
  144. statusCode, err := getWebsiteStatus(url)
  145. end := time.Now().UnixNano() / int64(time.Millisecond)
  146. if err != nil {
  147. log.Println(err.Error())
  148. return false, 0, 0
  149. } else {
  150. diff := end - start
  151. succ := false
  152. if statusCode >= 200 && statusCode < 300 {
  153. //OK
  154. succ = true
  155. } else if statusCode >= 300 && statusCode < 400 {
  156. //Redirection code
  157. succ = true
  158. } else {
  159. succ = false
  160. }
  161. return succ, diff, statusCode
  162. }
  163. }
  164. func getWebsiteStatus(url string) (int, error) {
  165. resp, err := http.Get(url)
  166. if err != nil {
  167. return 0, err
  168. }
  169. status_code := resp.StatusCode
  170. return status_code, nil
  171. }