monitoring_controller.rb 11 KB

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