sitegoose 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,9 @@
12
12
  # Sequel: SiteGoose.watch_database(DB), one line. A Sequel query
13
13
  # run on Active Record's connection is counted once, as Sequel's.
14
14
  # Mongo (the mongo gem, Mongoid): a global command subscriber, automatic.
15
+ # ClickHouse: the click_house gem's ClickHouse::Connection through
16
+ # SiteGoose.watch_database(connection), one line; an Active Record
17
+ # ClickHouse adapter (clickhouse-activerecord) through sql.active_record.
15
18
  #
16
19
  # A query is added to the request (or job) it ran in, and the request's
17
20
  # queries go into the minute's rows when it finishes, under the method and
@@ -20,19 +23,168 @@
20
23
  # off nothing is recorded; queries: false keeps Server speed without them.
21
24
 
22
25
  module SiteGoose
23
- class Queries
24
- FLUSH_EVERY = Performance::FLUSH_EVERY
26
+ # What Queries and Calls share (sdk/protocols/queries.md and calls.md,
27
+ # "Recording"): each timing is filed under the request (or job) it ran in,
28
+ # keyed by its two fields (db + statement, call method + host); when the
29
+ # request finishes they go into the minute's rows under the method and
30
+ # route Server speed recorded; outside any request or job they are
31
+ # "JOB" "(background)". Finished minutes are sent every 60 seconds, and
32
+ # everything on shutdown. The including class names FIELDS (its two key
33
+ # fields as sent), PATH, MOD (the name it logs under) and REQUEST (the
34
+ # thread-local the request's own map lives in, which Context.with clears).
35
+ module MinuteRows
36
+ FLUSH_EVERY = 60
25
37
  MAX_ROWS = 500
26
- # Distinct statements one request keeps; past it new ones are "(other)".
38
+ # Distinct keys one request keeps; past it new ones are "(other)".
27
39
  MAX_PER_REQUEST = 50
28
- # Keys in a minute: past MAX_KEYS new statements are "(other)", past
40
+ # Keys in a minute: past MAX_KEYS new ones are "(other)", past
29
41
  # HARD_MAX_KEYS nothing new is kept.
30
42
  MAX_KEYS = 200
31
43
  HARD_MAX_KEYS = 300
32
44
  # Minutes kept unsent (a platform that can't send flushes by hand).
33
45
  MAX_MINUTES = 5
34
- OTHER = QueryText::OTHER_STATEMENT
46
+ OTHER = "(other)"
35
47
  BACKGROUND = ["JOB", "(background)"].freeze
48
+
49
+ def self.minute
50
+ (Time.now.to_i / 60) * 60
51
+ end
52
+
53
+ # -> [count, errors, sum_ms, max_ms, buckets] as a hash.
54
+ def self.blank
55
+ { count: 0, errors: 0, sum_ms: 0.0, max_ms: 0.0, buckets: Array.new(Performance::BUCKET_EDGES_MS.size + 1, 0) }
56
+ end
57
+
58
+ def self.merge(into, from)
59
+ into[:count] += from[:count]
60
+ into[:errors] += from[:errors]
61
+ into[:sum_ms] += from[:sum_ms]
62
+ into[:max_ms] = from[:max_ms] if from[:max_ms] > into[:max_ms]
63
+ from[:buckets].each_with_index { |n, i| into[:buckets][i] += n }
64
+ into
65
+ end
66
+
67
+ def self.add(into, ms, failed)
68
+ into[:count] += 1
69
+ into[:errors] += 1 if failed
70
+ into[:sum_ms] += ms
71
+ into[:max_ms] = ms if ms > into[:max_ms]
72
+ into[:buckets][Performance.bucket_of(ms)] += 1
73
+ into
74
+ end
75
+
76
+ attr_reader :rows
77
+
78
+ def start_rows(core, server_name)
79
+ @core = core
80
+ @server_name = SiteGoose.text(server_name || SiteGoose.hostname, 100)
81
+ @rows = {}
82
+ @lock = Mutex.new
83
+ @job = core.valid? ? Periodic.new(FLUSH_EVERY) { flush(everything: false); FLUSH_EVERY } : nil
84
+ Forking.register(self)
85
+ end
86
+
87
+ # In a forked worker the parent's rows are the parent's to send.
88
+ def after_fork_in_child
89
+ @lock = Mutex.new
90
+ @rows = {}
91
+ end
92
+
93
+ def on?
94
+ @core.on?("performance")
95
+ end
96
+
97
+ # One timing (first, second: its two key fields) into its request's map,
98
+ # or straight into the minute's rows as background.
99
+ def file(first, second, ms, failed)
100
+ ms = ms.to_f
101
+ ms = 0.0 if ms.negative? || ms.nan?
102
+ if Context.request
103
+ mine = (Thread.current[self.class::REQUEST] ||= {})
104
+ key = [first, second]
105
+ key = [first, OTHER] if !mine.key?(key) && mine.size >= MAX_PER_REQUEST
106
+ MinuteRows.add(mine[key] ||= MinuteRows.blank, ms, failed)
107
+ else
108
+ one = MinuteRows.add(MinuteRows.blank, ms, failed)
109
+ @lock.synchronize { add_row(MinuteRows.minute, *BACKGROUND, first, second, one) }
110
+ end
111
+ end
112
+
113
+ # The request (or job) finished, and Server speed recorded it under
114
+ # method and route: its timings go into this minute's rows.
115
+ def finish(method, route)
116
+ mine = Thread.current[self.class::REQUEST]
117
+ Thread.current[self.class::REQUEST] = nil
118
+ return if mine.nil? || mine.empty? || !on?
119
+
120
+ minute = MinuteRows.minute
121
+ @lock.synchronize do
122
+ mine.each { |(first, second), agg| add_row(minute, method, route, first, second, agg) }
123
+ end
124
+ end
125
+
126
+ # Under @lock.
127
+ def add_row(minute, method, route, first, second, agg)
128
+ keys = @rows[minute]
129
+ unless keys
130
+ @rows.delete(@rows.keys.min) while @rows.size >= MAX_MINUTES
131
+ keys = @rows[minute] = {}
132
+ end
133
+ key = [method, route, first, second]
134
+ key = [method, route, first, OTHER] if !keys.key?(key) && keys.size >= MAX_KEYS
135
+ return if !keys.key?(key) && keys.size >= HARD_MAX_KEYS
136
+
137
+ MinuteRows.merge(keys[key] ||= MinuteRows.blank, agg)
138
+ end
139
+ private :add_row
140
+
141
+ def flush(everything: true)
142
+ current = MinuteRows.minute
143
+ ready = @lock.synchronize do
144
+ taken = @rows.select { |minute, _| everything || minute < current }
145
+ taken.each_key { |minute| @rows.delete(minute) }
146
+ taken
147
+ end
148
+ first_name, second_name = self.class::FIELDS
149
+ rows = ready.flat_map do |minute, keys|
150
+ at = Time.at(minute).utc.iso8601(3)
151
+ keys.map do |(method, route, first, second), v|
152
+ { "minute" => at, "method" => method, "route" => route, first_name => first, second_name => second,
153
+ "count" => v[:count], "errors" => v[:errors], "sum_ms" => v[:sum_ms].round(1),
154
+ "max_ms" => v[:max_ms].round(1), "buckets" => v[:buckets] }
155
+ end
156
+ end
157
+ rows.each_slice(MAX_ROWS) do |batch|
158
+ @core.request(self.class::MOD, self.class::PATH, auth: :bearer,
159
+ body: { "site_id" => @core.site_id, "server_name" => @server_name,
160
+ "runtime" => RUNTIME, "rows" => batch })
161
+ end
162
+ end
163
+
164
+ def stop_rows
165
+ @job&.stop
166
+ Forking.unregister(self)
167
+ flush
168
+ end
169
+ end
170
+
171
+ # The instances a class's hooks report to (Queries, Calls): the newest
172
+ # platform's that is still open. The class sets @open and @lock.
173
+ module OpenList
174
+ def active
175
+ @lock.synchronize { @open.last }
176
+ end
177
+
178
+ def opened(item)
179
+ @lock.synchronize { @open << item }
180
+ end
181
+
182
+ def closed(item)
183
+ @lock.synchronize { @open.delete(item) }
184
+ end
185
+ end
186
+
187
+ class Queries
36
188
  # The request's own queries, fiber-local beside Context's fields: Context.with
37
189
  # starts each request or job with none.
38
190
  REQUEST = Context::QUERIES
@@ -45,21 +197,9 @@ module SiteGoose
45
197
  @lock = Mutex.new
46
198
  @cache = {}
47
199
  @hooked = {}
200
+ extend OpenList
48
201
 
49
202
  class << self
50
- # The platform's Queries that hooks report to: the newest still open.
51
- def active
52
- @lock.synchronize { @open.last }
53
- end
54
-
55
- def opened(queries)
56
- @lock.synchronize { @open << queries }
57
- end
58
-
59
- def closed(queries)
60
- @lock.synchronize { @open.delete(queries) }
61
- end
62
-
63
203
  # The statement as stored ("" to leave it out); the same query text
64
204
  # comes round again and again, so the answer is kept.
65
205
  def statement(text, db)
@@ -97,28 +237,6 @@ module SiteGoose
97
237
  nil
98
238
  end
99
239
 
100
- def blank
101
- { count: 0, errors: 0, sum_ms: 0.0, max_ms: 0.0, buckets: Array.new(Performance::BUCKET_EDGES_MS.size + 1, 0) }
102
- end
103
-
104
- def merge(into, from)
105
- into[:count] += from[:count]
106
- into[:errors] += from[:errors]
107
- into[:sum_ms] += from[:sum_ms]
108
- into[:max_ms] = from[:max_ms] if from[:max_ms] > into[:max_ms]
109
- from[:buckets].each_with_index { |n, i| into[:buckets][i] += n }
110
- into
111
- end
112
-
113
- def add(into, ms, failed)
114
- into[:count] += 1
115
- into[:errors] += 1 if failed
116
- into[:sum_ms] += ms
117
- into[:max_ms] = ms if ms > into[:max_ms]
118
- into[:buckets][Performance.bucket_of(ms)] += 1
119
- into
120
- end
121
-
122
240
  # ---- Hooks: installed once per process, for every platform ----
123
241
 
124
242
  def install
@@ -165,6 +283,7 @@ module SiteGoose
165
283
  when /sqlite/ then "sqlite"
166
284
  when /sqlserver|mssql/ then "mssql"
167
285
  when /oracle/ then "oracle"
286
+ when /clickhouse/ then "clickhouse"
168
287
  else "other"
169
288
  end
170
289
  end
@@ -186,6 +305,7 @@ module SiteGoose
186
305
  when "sqlite" then "sqlite"
187
306
  when "mssql" then "mssql"
188
307
  when "oracle" then "oracle"
308
+ when "clickhouse" then "clickhouse"
189
309
  else "other"
190
310
  end
191
311
  end
@@ -196,6 +316,63 @@ module SiteGoose
196
316
  database.extend(SequelHook) unless database.singleton_class.include?(SequelHook)
197
317
  database
198
318
  end
319
+
320
+ # Times one click_house gem connection's public query methods. Only the
321
+ # methods the object has are wrapped, on that object alone.
322
+ def watch_clickhouse(connection)
323
+ return connection if connection.singleton_class.include?(ClickHouseHook)
324
+
325
+ wrapped = ClickHouseHook::METHODS.select { |name| connection.respond_to?(name) }
326
+ hook = Module.new do
327
+ include ClickHouseHook
328
+
329
+ wrapped.each do |name|
330
+ define_method(name) do |*args, **options, &block|
331
+ text = ClickHouseHook.text_of(name, args)
332
+ return super(*args, **options, &block) if text.nil? || Queries.timing? || Queries.active.nil?
333
+
334
+ Queries.time("clickhouse", text) { super(*args, **options, &block) }
335
+ end
336
+ end
337
+ end
338
+ connection.extend(hook)
339
+ connection
340
+ end
341
+
342
+ # Runs the block as one timed query, recorded when it ends (failed
343
+ # when it raised); queries the block runs underneath aren't timed again,
344
+ # and neither are its HTTP requests (Calls).
345
+ def time(db, text)
346
+ started = SiteGoose.clock
347
+ failed = false
348
+ begin
349
+ timing { yield }
350
+ rescue StandardError
351
+ failed = true
352
+ raise
353
+ ensure
354
+ record(db, text, (SiteGoose.clock - started) * 1000, failed: failed)
355
+ end
356
+ end
357
+ end
358
+
359
+ # The click_house gem (ClickHouse::Connection): select_all, select_one,
360
+ # select_value and execute carry the SQL; insert names its table, and
361
+ # its rows are never read. The gem answers once the whole result is
362
+ # read, so the time is the query's to the end.
363
+ module ClickHouseHook
364
+ METHODS = %i[select_all select_one select_value execute insert].freeze
365
+
366
+ def self.text_of(name, args)
367
+ first = args[0]
368
+ case name
369
+ when :insert then first.nil? ? nil : "INSERT INTO #{first}"
370
+ else first.is_a?(String) ? first : nil
371
+ end
372
+ rescue StandardError
373
+ # A table name that can't be written: the call runs untimed.
374
+ nil
375
+ end
199
376
  end
200
377
 
201
378
  # Extends one Sequel::Database (Sequel's own extensions wrap the same
@@ -255,7 +432,7 @@ module SiteGoose
255
432
 
256
433
  text = MongoSubscriber.text(name, event.command)
257
434
  @lock.synchronize do
258
- @waiting.delete(@waiting.keys.first) while @waiting.size >= WAITING_MAX
435
+ @waiting.shift while @waiting.size >= WAITING_MAX
259
436
  @waiting[event.request_id] = text
260
437
  end
261
438
  rescue StandardError
@@ -278,29 +455,17 @@ module SiteGoose
278
455
  end
279
456
  end
280
457
 
281
- attr_reader :rows
458
+ include MinuteRows
459
+ FIELDS = %w[db statement].freeze
460
+ PATH = "/events/server-queries"
461
+ MOD = "queries"
282
462
 
283
463
  def initialize(core, server_name: nil)
284
- @core = core
285
- @server_name = SiteGoose.text(server_name || SiteGoose.hostname, 100)
286
- @rows = {}
287
- @lock = Mutex.new
288
- @job = core.valid? ? Periodic.new(FLUSH_EVERY) { flush(everything: false); FLUSH_EVERY } : nil
289
- Forking.register(self)
464
+ start_rows(core, server_name)
290
465
  Queries.opened(self)
291
466
  Queries.install
292
467
  end
293
468
 
294
- # In a forked worker the parent's rows are the parent's to send.
295
- def after_fork_in_child
296
- @lock = Mutex.new
297
- @rows = {}
298
- end
299
-
300
- def on?
301
- @core.on?("performance")
302
- end
303
-
304
469
  # One finished query: into its request's (or job's) queries, or, with
305
470
  # none around it, straight into the minute's rows as background.
306
471
  def record(db, text, ms, failed: false)
@@ -310,89 +475,27 @@ module SiteGoose
310
475
  statement = Queries.statement(text, db)
311
476
  return if statement.empty?
312
477
 
313
- ms = ms.to_f
314
- ms = 0.0 if ms.negative? || ms.nan?
315
- if Context.request
316
- mine = (Thread.current[REQUEST] ||= {})
317
- key = [db, statement]
318
- key = [db, OTHER] if !mine.key?(key) && mine.size >= MAX_PER_REQUEST
319
- Queries.add(mine[key] ||= Queries.blank, ms, failed)
320
- else
321
- one = Queries.add(Queries.blank, ms, failed)
322
- @lock.synchronize { add_row(Queries.minute, *BACKGROUND, db, statement, one) }
323
- end
324
- end
325
-
326
- def self.minute
327
- (Time.now.to_i / 60) * 60
328
- end
329
-
330
- # The request (or job) finished, and Server speed recorded it under
331
- # method and route: its queries go into this minute's rows.
332
- def finish(method, route)
333
- mine = Thread.current[REQUEST]
334
- Thread.current[REQUEST] = nil
335
- return if mine.nil? || mine.empty? || !on?
336
-
337
- minute = Queries.minute
338
- @lock.synchronize do
339
- mine.each { |(db, statement), agg| add_row(minute, method, route, db, statement, agg) }
340
- end
341
- end
342
-
343
- # Under @lock.
344
- def add_row(minute, method, route, db, statement, agg)
345
- keys = @rows[minute]
346
- unless keys
347
- @rows.delete(@rows.keys.min) while @rows.size >= MAX_MINUTES
348
- keys = @rows[minute] = {}
349
- end
350
- key = [method, route, db, statement]
351
- key = [method, route, db, OTHER] if !keys.key?(key) && keys.size >= MAX_KEYS
352
- return if !keys.key?(key) && keys.size >= HARD_MAX_KEYS
353
-
354
- Queries.merge(keys[key] ||= Queries.blank, agg)
355
- end
356
- private :add_row
357
-
358
- def flush(everything: true)
359
- current = Queries.minute
360
- ready = @lock.synchronize do
361
- taken = @rows.select { |minute, _| everything || minute < current }
362
- taken.each_key { |minute| @rows.delete(minute) }
363
- taken
364
- end
365
- rows = ready.flat_map do |minute, keys|
366
- at = Time.at(minute).utc.iso8601(3)
367
- keys.map do |(method, route, db, statement), v|
368
- { "minute" => at, "method" => method, "route" => route, "db" => db, "statement" => statement,
369
- "count" => v[:count], "errors" => v[:errors], "sum_ms" => v[:sum_ms].round(1),
370
- "max_ms" => v[:max_ms].round(1), "buckets" => v[:buckets] }
371
- end
372
- end
373
- rows.each_slice(MAX_ROWS) do |batch|
374
- @core.request("queries", "/events/server-queries", auth: :bearer,
375
- body: { "site_id" => @core.site_id, "server_name" => @server_name,
376
- "runtime" => RUNTIME, "rows" => batch })
377
- end
478
+ file(db, statement, ms, failed)
378
479
  end
379
480
 
380
481
  def close
381
- @job&.stop
382
- Forking.unregister(self)
383
482
  Queries.closed(self)
384
- flush
483
+ stop_rows
385
484
  end
386
485
  end
387
486
 
388
- # Times every query this Sequel database runs (Health -> Server speed ->
389
- # Queries): SiteGoose.watch_database(DB). Rails' Active Record and
390
- # the mongo gem are caught on their own.
487
+ # Times every query this database object runs (Health -> Server speed ->
488
+ # Queries): SiteGoose.watch_database(DB) for a Sequel::Database or a
489
+ # click_house gem ClickHouse::Connection. Rails' Active Record and the
490
+ # mongo gem are caught on their own.
391
491
  def self.watch_database(database)
392
492
  if defined?(::Sequel::Database) && database.is_a?(::Sequel::Database)
393
493
  Queries.watch_sequel(database)
494
+ elsif defined?(::ClickHouse::Connection) && database.is_a?(::ClickHouse::Connection)
495
+ Queries.watch_clickhouse(database)
394
496
  else
395
- warn "[analytics-platform] watch_database: #{database.class} is not a Sequel::Database; Active Record and Mongo are timed on their own"
497
+ warn "[analytics-platform] watch_database: #{database.class} is not a Sequel::Database or a ClickHouse::Connection; " \
498
+ "Active Record and Mongo are timed on their own"
396
499
  end
397
500
  database
398
501
  end