monitoring_controller.rb 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class MonitoringController < ApplicationController
  3. prepend_before_action -> { authentication_check(permission: 'admin.monitoring') }, except: %i[health_check status]
  4. skip_before_action :verify_csrf_token
  5. =begin
  6. Resource:
  7. GET /api/v1/monitoring/health_check?token=XXX
  8. Response:
  9. {
  10. "healthy": true,
  11. "message": "success",
  12. }
  13. {
  14. "healthy": false,
  15. "message": "authentication of XXX failed; issue #2",
  16. "issues": ["authentication of XXX failed", "issue #2"],
  17. }
  18. Test:
  19. curl http://localhost/api/v1/monitoring/health_check?token=XXX
  20. =end
  21. def health_check
  22. token_or_permission_check
  23. issues = []
  24. actions = Set.new
  25. # channel check
  26. last_run_tolerance = Time.zone.now - 1.hour
  27. Channel.where(active: true).each do |channel|
  28. # inbound channel
  29. if channel.status_in == 'error'
  30. message = "Channel: #{channel.area} in "
  31. %w[host user uid].each do |key|
  32. next if channel.options[key].blank?
  33. message += "key:#{channel.options[key]};"
  34. end
  35. issues.push "#{message} #{channel.last_log_in}"
  36. end
  37. if channel.preferences && channel.preferences['last_fetch'] && channel.preferences['last_fetch'] < last_run_tolerance
  38. issues.push "#{message} channel is active but not fetched for 1 hour"
  39. end
  40. # outbound channel
  41. next if channel.status_out != 'error'
  42. message = "Channel: #{channel.area} out "
  43. %w[host user uid].each do |key|
  44. next if channel.options[key].blank?
  45. message += "key:#{channel.options[key]};"
  46. end
  47. issues.push "#{message} #{channel.last_log_out}"
  48. end
  49. # unprocessable mail check
  50. directory = Rails.root.join('tmp', 'unprocessable_mail').to_s
  51. if File.exist?(directory)
  52. count = 0
  53. Dir.glob("#{directory}/*.eml") do |_entry|
  54. count += 1
  55. end
  56. if count.nonzero?
  57. issues.push "unprocessable mails: #{count}"
  58. end
  59. end
  60. # scheduler check
  61. Scheduler.where(active: true).where.not(last_run: nil).each do |scheduler|
  62. next if scheduler.period <= 300
  63. next if scheduler.last_run + scheduler.period.seconds > Time.zone.now - 5.minutes
  64. issues.push 'scheduler not running'
  65. break
  66. end
  67. if Scheduler.where(active: true, last_run: nil).count == Scheduler.where(active: true).count
  68. issues.push 'scheduler not running'
  69. end
  70. Scheduler.failed_jobs.each do |job|
  71. issues.push "Failed to run scheduled job '#{job.name}'. Cause: #{job.error_message}"
  72. actions.add(:restart_failed_jobs)
  73. end
  74. # failed jobs check
  75. failed_jobs = Delayed::Job.where('attempts > 0')
  76. count_failed_jobs = failed_jobs.count
  77. if count_failed_jobs > 10
  78. issues.push "#{count_failed_jobs} failing background jobs."
  79. end
  80. listed_failed_jobs = failed_jobs.select(:handler, :attempts).limit(10)
  81. listed_failed_jobs.group_by(&:name).each_with_index do |(name, jobs), index|
  82. attempts = jobs.map(&:attempts).sum
  83. issues.push "Failed to run background job ##{index += 1} '#{name}' #{jobs.count} time(s) with #{attempts} attempt(s)."
  84. end
  85. # import jobs
  86. import_backends = ImportJob.backends
  87. # failed import jobs
  88. import_backends.each do |backend|
  89. job = ImportJob.where(
  90. name: backend,
  91. dry_run: false,
  92. ).where('finished_at >= ?', 5.minutes.ago).limit(1).first
  93. next if job.blank?
  94. next if !job.result.is_a?(Hash)
  95. error_message = job.result[:error]
  96. next if error_message.blank?
  97. issues.push "Failed to run import backend '#{backend}'. Cause: #{error_message}"
  98. end
  99. # stuck import jobs
  100. import_backends.each do |backend|
  101. job = ImportJob.where(
  102. name: backend,
  103. dry_run: false,
  104. finished_at: nil,
  105. ).where('updated_at <= ?', 5.minutes.ago).limit(1).first
  106. next if job.blank?
  107. issues.push "Stuck import backend '#{backend}' detected. Last update: #{job.updated_at}"
  108. end
  109. token = Setting.get('monitoring_token')
  110. if issues.blank?
  111. result = {
  112. healthy: true,
  113. message: 'success',
  114. token: token,
  115. }
  116. render json: result
  117. return
  118. end
  119. result = {
  120. healthy: false,
  121. message: issues.join(';'),
  122. issues: issues,
  123. actions: actions,
  124. token: token,
  125. }
  126. render json: result
  127. end
  128. =begin
  129. Resource:
  130. GET /api/v1/monitoring/status?token=XXX
  131. Response:
  132. {
  133. "agents": 8123,
  134. "last_login": "2016-11-21T14:14:14Z",
  135. "counts": {
  136. "users": 12313,
  137. "tickets": 23123,
  138. "ticket_articles": 131451,
  139. },
  140. "last_created_at": {
  141. "users": "2016-11-21T14:14:14Z",
  142. "tickets": "2016-11-21T14:14:14Z",
  143. "ticket_articles": "2016-11-21T14:14:14Z",
  144. },
  145. }
  146. Test:
  147. curl http://localhost/api/v1/monitoring/status?token=XXX
  148. =end
  149. def status
  150. token_or_permission_check
  151. last_login = nil
  152. last_login_user = User.where('last_login IS NOT NULL').order(last_login: :desc).limit(1).first
  153. if last_login_user
  154. last_login = last_login_user.last_login
  155. end
  156. status = {
  157. counts: {},
  158. last_created_at: {},
  159. last_login: last_login,
  160. agents: User.with_permissions('ticket.agent').count,
  161. }
  162. map = {
  163. users: User,
  164. groups: Group,
  165. overviews: Overview,
  166. tickets: Ticket,
  167. ticket_articles: Ticket::Article,
  168. }
  169. map.each do |key, class_name|
  170. status[:counts][key] = class_name.count
  171. last = class_name.last
  172. status[:last_created_at][key] = last&.created_at
  173. end
  174. render json: status
  175. end
  176. def token
  177. access_check
  178. token = SecureRandom.urlsafe_base64(40)
  179. Setting.set('monitoring_token', token)
  180. result = {
  181. token: token,
  182. }
  183. render json: result, status: :created
  184. end
  185. def restart_failed_jobs
  186. access_check
  187. Scheduler.restart_failed_jobs
  188. render json: {}, status: :ok
  189. end
  190. private
  191. def token_or_permission_check
  192. user = authentication_check_only(permission: 'admin.monitoring')
  193. return if user
  194. return if Setting.get('monitoring_token') == params[:token]
  195. raise Exceptions::NotAuthorized
  196. end
  197. def access_check
  198. return if Permission.find_by(name: 'admin.monitoring', active: true)
  199. raise Exceptions::NotAuthorized
  200. end
  201. end