monitoring_controller.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class MonitoringController < ApplicationController
  3. prepend_before_action { authorize! }
  4. prepend_before_action -> { authentication_check }, except: %i[health_check status amount_check]
  5. prepend_before_action -> { authentication_check_only }, only: %i[health_check status amount_check]
  6. skip_before_action :verify_csrf_token
  7. =begin
  8. Resource:
  9. GET /api/v1/monitoring/health_check?token=XXX
  10. Response:
  11. {
  12. "healthy": true,
  13. "message": "success",
  14. }
  15. {
  16. "healthy": false,
  17. "message": "authentication of XXX failed; issue #2",
  18. "issues": ["authentication of XXX failed", "issue #2"],
  19. }
  20. Test:
  21. curl http://localhost/api/v1/monitoring/health_check?token=XXX
  22. =end
  23. def health_check
  24. issues = []
  25. actions = Set.new
  26. # channel check
  27. last_run_tolerance = Time.zone.now - 1.hour
  28. Channel.where(active: true).each do |channel|
  29. # inbound channel
  30. if channel.status_in == 'error'
  31. message = "Channel: #{channel.area} in "
  32. %w[host user uid].each do |key|
  33. next if channel.options[key].blank?
  34. message += "key:#{channel.options[key]};"
  35. end
  36. issues.push "#{message} #{channel.last_log_in}"
  37. end
  38. if channel.preferences && channel.preferences['last_fetch'] && channel.preferences['last_fetch'] < last_run_tolerance
  39. diff = Time.zone.now - channel.preferences['last_fetch']
  40. issues.push "#{message} channel is active but not fetched for #{helpers.time_ago_in_words(Time.zone.now - diff.seconds)}"
  41. end
  42. # outbound channel
  43. next if channel.status_out != 'error'
  44. message = "Channel: #{channel.area} out "
  45. %w[host user uid].each do |key|
  46. next if channel.options[key].blank?
  47. message += "key:#{channel.options[key]};"
  48. end
  49. issues.push "#{message} #{channel.last_log_out}"
  50. end
  51. # unprocessable mail check
  52. directory = Rails.root.join('tmp/unprocessable_mail').to_s
  53. if File.exist?(directory)
  54. count = 0
  55. Dir.glob("#{directory}/*.eml") do |_entry|
  56. count += 1
  57. end
  58. if count.nonzero?
  59. issues.push "unprocessable mails: #{count}"
  60. end
  61. end
  62. # scheduler running check
  63. Scheduler.where('active = ? AND period > 300', true).where.not(last_run: nil).order(last_run: :asc, period: :asc).each do |scheduler|
  64. diff = Time.zone.now - (scheduler.last_run + scheduler.period.seconds)
  65. next if diff < 8.minutes
  66. issues.push "scheduler may not run (last execution of #{scheduler.method} #{helpers.time_ago_in_words(Time.zone.now - diff.seconds)} over) - please contact your system administrator"
  67. break
  68. end
  69. if Scheduler.where(active: true, last_run: nil).count == Scheduler.where(active: true).count
  70. issues.push 'scheduler not running'
  71. end
  72. Scheduler.failed_jobs.each do |job|
  73. issues.push "Failed to run scheduled job '#{job.name}'. Cause: #{job.error_message}"
  74. actions.add(:restart_failed_jobs)
  75. end
  76. # failed jobs check
  77. failed_jobs = Delayed::Job.where('attempts > 0')
  78. count_failed_jobs = failed_jobs.count
  79. if count_failed_jobs > 10
  80. issues.push "#{count_failed_jobs} failing background jobs"
  81. end
  82. handler_attempts_map = {}
  83. failed_jobs.order(:created_at).limit(10).each do |job|
  84. job_name = if job.class.name == 'Delayed::Backend::ActiveRecord::Job'.freeze && job.payload_object.respond_to?(:job_data)
  85. job.payload_object.job_data['job_class']
  86. else
  87. job.name
  88. end
  89. handler_attempts_map[job_name] ||= {
  90. count: 0,
  91. attempts: 0,
  92. }
  93. handler_attempts_map[job_name][:count] += 1
  94. handler_attempts_map[job_name][:attempts] += job.attempts
  95. end
  96. Hash[handler_attempts_map.sort].each_with_index do |(job_name, job_data), index|
  97. issues.push "Failed to run background job ##{index + 1} '#{job_name}' #{job_data[:count]} time(s) with #{job_data[:attempts]} attempt(s)."
  98. end
  99. # job count check
  100. total_jobs = Delayed::Job.where('created_at < ?', Time.zone.now - 15.minutes).count
  101. if total_jobs > 8000
  102. issues.push "#{total_jobs} background jobs in queue"
  103. end
  104. # import jobs
  105. import_backends = ImportJob.backends
  106. # failed import jobs
  107. import_backends.each do |backend|
  108. job = ImportJob.where(
  109. name: backend,
  110. dry_run: false,
  111. ).where('finished_at >= ?', 5.minutes.ago).limit(1).first
  112. next if job.blank?
  113. next if !job.result.is_a?(Hash)
  114. error_message = job.result[:error]
  115. next if error_message.blank?
  116. issues.push "Failed to run import backend '#{backend}'. Cause: #{error_message}"
  117. end
  118. # stuck import jobs
  119. import_backends.each do |backend|
  120. job = ImportJob.where(
  121. name: backend,
  122. dry_run: false,
  123. finished_at: nil,
  124. ).where('updated_at <= ?', 5.minutes.ago).limit(1).first
  125. next if job.blank?
  126. issues.push "Stuck import backend '#{backend}' detected. Last update: #{job.updated_at}"
  127. end
  128. # stuck data privacy tasks
  129. DataPrivacyTask.where.not(state: 'completed').where('updated_at <= ?', 30.minutes.ago).find_each do |task|
  130. issues.push "Stuck data privacy task (ID #{task.id}) detected. Last update: #{task.updated_at}"
  131. end
  132. token = Setting.get('monitoring_token')
  133. if issues.blank?
  134. result = {
  135. healthy: true,
  136. message: 'success',
  137. issues: issues,
  138. token: token,
  139. }
  140. render json: result
  141. return
  142. end
  143. result = {
  144. healthy: false,
  145. message: issues.join(';'),
  146. issues: issues,
  147. actions: actions,
  148. token: token,
  149. }
  150. render json: result
  151. end
  152. =begin
  153. Resource:
  154. GET /api/v1/monitoring/status?token=XXX
  155. Response:
  156. {
  157. "agents": 8123,
  158. "last_login": "2016-11-21T14:14:14Z",
  159. "counts": {
  160. "users": 12313,
  161. "tickets": 23123,
  162. "ticket_articles": 131451,
  163. },
  164. "last_created_at": {
  165. "users": "2016-11-21T14:14:14Z",
  166. "tickets": "2016-11-21T14:14:14Z",
  167. "ticket_articles": "2016-11-21T14:14:14Z",
  168. },
  169. }
  170. Test:
  171. curl http://localhost/api/v1/monitoring/status?token=XXX
  172. =end
  173. def status
  174. last_login = nil
  175. last_login_user = User.where('last_login IS NOT NULL').order(last_login: :desc).limit(1).first
  176. if last_login_user
  177. last_login = last_login_user.last_login
  178. end
  179. status = {
  180. counts: {},
  181. last_created_at: {},
  182. last_login: last_login,
  183. agents: User.with_permissions('ticket.agent').count,
  184. }
  185. map = {
  186. users: User,
  187. groups: Group,
  188. overviews: Overview,
  189. tickets: Ticket,
  190. ticket_articles: Ticket::Article,
  191. text_modules: TextModule,
  192. object_manager_attributes: ObjectManager::Attribute,
  193. knowledge_base_categories: KnowledgeBase::Category,
  194. knowledge_base_answers: KnowledgeBase::Answer,
  195. }
  196. map.each do |key, class_name|
  197. status[:counts][key] = class_name.count
  198. last = class_name.last
  199. status[:last_created_at][key] = last&.created_at
  200. end
  201. if ActiveRecord::Base.connection_config[:adapter] == 'postgresql'
  202. sql = 'SELECT SUM(CAST(coalesce(size, \'0\') AS INTEGER)) FROM stores WHERE id IN (SELECT MAX(id) FROM stores GROUP BY store_file_id)'
  203. records_array = ActiveRecord::Base.connection.exec_query(sql)
  204. if records_array[0] && records_array[0]['sum']
  205. sum = records_array[0]['sum']
  206. status[:storage] = {
  207. kB: sum / 1024,
  208. MB: sum / 1024 / 1024,
  209. GB: sum / 1024 / 1024 / 1024,
  210. }
  211. end
  212. end
  213. render json: status
  214. end
  215. =begin
  216. get counts about created ticket in certain time slot. s, m, h and d possible.
  217. Resource:
  218. GET /api/v1/monitoring/amount_check?token=XXX&max_warning=2000&max_critical=3000&periode=1h
  219. GET /api/v1/monitoring/amount_check?token=XXX&min_warning=2000&min_critical=3000&periode=1h
  220. GET /api/v1/monitoring/amount_check?token=XXX&periode=1h
  221. Response:
  222. {
  223. "state": "ok",
  224. "message": "",
  225. "count": 123,
  226. }
  227. {
  228. "state": "warning",
  229. "message": "limit of 2000 tickets in 1h reached",
  230. "count": 123,
  231. }
  232. {
  233. "state": "critical",
  234. "message": "limit of 3000 tickets in 1h reached",
  235. "count": 123,
  236. }
  237. Test:
  238. curl http://localhost/api/v1/monitoring/amount_check?token=XXX&max_warning=2000&max_critical=3000&periode=1h
  239. curl http://localhost/api/v1/monitoring/amount_check?token=XXX&min_warning=2000&min_critical=3000&periode=1h
  240. curl http://localhost/api/v1/monitoring/amount_check?token=XXX&periode=1h
  241. =end
  242. def amount_check
  243. raise Exceptions::UnprocessableEntity, 'periode is missing!' if params[:periode].blank?
  244. scale = params[:periode][-1, 1]
  245. raise Exceptions::UnprocessableEntity, 'periode need to have s, m, h or d as last!' if !scale.match?(/^(s|m|h|d)$/)
  246. periode = params[:periode][0, params[:periode].length - 1]
  247. raise Exceptions::UnprocessableEntity, 'periode need to be an integer!' if periode.to_i.zero?
  248. case scale
  249. when 's'
  250. created_at = Time.zone.now - periode.to_i.seconds
  251. when 'm'
  252. created_at = Time.zone.now - periode.to_i.minutes
  253. when 'h'
  254. created_at = Time.zone.now - periode.to_i.hours
  255. when 'd'
  256. created_at = Time.zone.now - periode.to_i.days
  257. end
  258. map = [
  259. { param: :max_critical, notice: 'critical', type: 'gt' },
  260. { param: :min_critical, notice: 'critical', type: 'lt' },
  261. { param: :max_warning, notice: 'warning', type: 'gt' },
  262. { param: :min_warning, notice: 'warning', type: 'lt' },
  263. ]
  264. result = {}
  265. state_param = false
  266. map.each do |row|
  267. next if params[row[:param]].blank?
  268. raise Exceptions::UnprocessableEntity, "#{row[:param]} need to be an integer!" if params[row[:param]].to_i.zero?
  269. state_param = true
  270. count = Ticket.where('created_at >= ?', created_at).count
  271. if row[:type] == 'gt'
  272. if count > params[row[:param]].to_i
  273. result = {
  274. state: row[:notice],
  275. message: "The limit of #{params[row[:param]]} was exceeded with #{count} in the last #{params[:periode]}",
  276. count: count,
  277. }
  278. break
  279. end
  280. next
  281. end
  282. next if count > params[row[:param]].to_i
  283. result = {
  284. state: row[:notice],
  285. message: "The minimum of #{params[row[:param]]} was undercut by #{count} in the last #{params[:periode]}",
  286. count: count,
  287. }
  288. break
  289. end
  290. if result.blank?
  291. result = {
  292. state: 'ok',
  293. count: Ticket.where('created_at >= ?', created_at).count,
  294. }
  295. end
  296. if state_param == false
  297. result.delete(:state)
  298. end
  299. render json: result
  300. end
  301. def token
  302. token = SecureRandom.urlsafe_base64(40)
  303. Setting.set('monitoring_token', token)
  304. result = {
  305. token: token,
  306. }
  307. render json: result, status: :created
  308. end
  309. def restart_failed_jobs
  310. Scheduler.restart_failed_jobs
  311. render json: {}, status: :ok
  312. end
  313. end