monitoring_controller.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. token = Setting.get('monitoring_token')
  129. if issues.blank?
  130. result = {
  131. healthy: true,
  132. message: 'success',
  133. token: token,
  134. }
  135. render json: result
  136. return
  137. end
  138. result = {
  139. healthy: false,
  140. message: issues.join(';'),
  141. issues: issues,
  142. actions: actions,
  143. token: token,
  144. }
  145. render json: result
  146. end
  147. =begin
  148. Resource:
  149. GET /api/v1/monitoring/status?token=XXX
  150. Response:
  151. {
  152. "agents": 8123,
  153. "last_login": "2016-11-21T14:14:14Z",
  154. "counts": {
  155. "users": 12313,
  156. "tickets": 23123,
  157. "ticket_articles": 131451,
  158. },
  159. "last_created_at": {
  160. "users": "2016-11-21T14:14:14Z",
  161. "tickets": "2016-11-21T14:14:14Z",
  162. "ticket_articles": "2016-11-21T14:14:14Z",
  163. },
  164. }
  165. Test:
  166. curl http://localhost/api/v1/monitoring/status?token=XXX
  167. =end
  168. def status
  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. raise Exceptions::UnprocessableEntity, 'periode is missing!' if params[:periode].blank?
  239. scale = params[:periode][-1, 1]
  240. raise Exceptions::UnprocessableEntity, 'periode need to have s, m, h or d as last!' if !scale.match?(/^(s|m|h|d)$/)
  241. periode = params[:periode][0, params[:periode].length - 1]
  242. raise Exceptions::UnprocessableEntity, 'periode need to be an integer!' if periode.to_i.zero?
  243. if scale == 's'
  244. created_at = Time.zone.now - periode.to_i.seconds
  245. elsif scale == 'm'
  246. created_at = Time.zone.now - periode.to_i.minutes
  247. elsif scale == 'h'
  248. created_at = Time.zone.now - periode.to_i.hours
  249. elsif scale == 'd'
  250. created_at = Time.zone.now - periode.to_i.days
  251. end
  252. map = [
  253. { param: :max_critical, notice: 'critical', type: 'gt' },
  254. { param: :min_critical, notice: 'critical', type: 'lt' },
  255. { param: :max_warning, notice: 'warning', type: 'gt' },
  256. { param: :min_warning, notice: 'warning', type: 'lt' },
  257. ]
  258. result = {}
  259. state_param = false
  260. map.each do |row|
  261. next if params[row[:param]].blank?
  262. raise Exceptions::UnprocessableEntity, "#{row[:param]} need to be an integer!" if params[row[:param]].to_i.zero?
  263. state_param = true
  264. count = Ticket.where('created_at >= ?', created_at).count
  265. if row[:type] == 'gt'
  266. if count > params[row[:param]].to_i
  267. result = {
  268. state: row[:notice],
  269. message: "The limit of #{params[row[:param]]} was exceeded with #{count} in the last #{params[:periode]}",
  270. count: count,
  271. }
  272. break
  273. end
  274. next
  275. end
  276. next if count > params[row[:param]].to_i
  277. result = {
  278. state: row[:notice],
  279. message: "The minimum of #{params[row[:param]]} was undercut by #{count} in the last #{params[:periode]}",
  280. count: count,
  281. }
  282. break
  283. end
  284. if result.blank?
  285. result = {
  286. state: 'ok',
  287. count: Ticket.where('created_at >= ?', created_at).count,
  288. }
  289. end
  290. if state_param == false
  291. result.delete(:state)
  292. end
  293. render json: result
  294. end
  295. def token
  296. token = SecureRandom.urlsafe_base64(40)
  297. Setting.set('monitoring_token', token)
  298. result = {
  299. token: token,
  300. }
  301. render json: result, status: :created
  302. end
  303. def restart_failed_jobs
  304. Scheduler.restart_failed_jobs
  305. render json: {}, status: :ok
  306. end
  307. end