tingyun_rpm 1.0.6

Sign up to get free protection for your applications and to get access to all the features.
Files changed (147) hide show
  1. checksums.yaml +7 -0
  2. data/.DS_Store +0 -0
  3. data/.gitignore +14 -0
  4. data/.travis.yml +4 -0
  5. data/CODE_OF_CONDUCT.md +13 -0
  6. data/Gemfile +3 -0
  7. data/Guardfile +25 -0
  8. data/LICENSE.txt +22 -0
  9. data/README.md +41 -0
  10. data/cert/cacert.pem +0 -0
  11. data/lib/ting_yun/agent/agent.rb +128 -0
  12. data/lib/ting_yun/agent/class_methods.rb +21 -0
  13. data/lib/ting_yun/agent/collector/base_sampler.rb +2 -0
  14. data/lib/ting_yun/agent/collector/error_collector/error_trace_array.rb +88 -0
  15. data/lib/ting_yun/agent/collector/error_collector/noticed_error.rb +129 -0
  16. data/lib/ting_yun/agent/collector/error_collector.rb +165 -0
  17. data/lib/ting_yun/agent/collector/middle_ware_collector/cpu_sampler.rb +68 -0
  18. data/lib/ting_yun/agent/collector/middle_ware_collector/memory_sampler.rb +139 -0
  19. data/lib/ting_yun/agent/collector/middle_ware_collector/middle_ware.rb +13 -0
  20. data/lib/ting_yun/agent/collector/middle_ware_collector/sampler.rb +59 -0
  21. data/lib/ting_yun/agent/collector/middle_ware_collector.rb +80 -0
  22. data/lib/ting_yun/agent/collector/sql_sampler.rb +299 -0
  23. data/lib/ting_yun/agent/collector/stats_engine/metric_stats.rb +170 -0
  24. data/lib/ting_yun/agent/collector/stats_engine/stats_hash.rb +172 -0
  25. data/lib/ting_yun/agent/collector/stats_engine.rb +28 -0
  26. data/lib/ting_yun/agent/collector/transaction_sampler/slowest_sample_buffer.rb +25 -0
  27. data/lib/ting_yun/agent/collector/transaction_sampler/transaction_sample_buffer_base.rb +96 -0
  28. data/lib/ting_yun/agent/collector/transaction_sampler.rb +226 -0
  29. data/lib/ting_yun/agent/container_data_manager.rb +94 -0
  30. data/lib/ting_yun/agent/cross_app/cross_app_monitor.rb +131 -0
  31. data/lib/ting_yun/agent/cross_app/cross_app_tracing.rb +202 -0
  32. data/lib/ting_yun/agent/cross_app/inbound_request_monitor.rb +22 -0
  33. data/lib/ting_yun/agent/database.rb +410 -0
  34. data/lib/ting_yun/agent/datastore/metric_helper.rb +82 -0
  35. data/lib/ting_yun/agent/datastore/mongo.rb +44 -0
  36. data/lib/ting_yun/agent/datastore.rb +33 -0
  37. data/lib/ting_yun/agent/dispatcher.rb +39 -0
  38. data/lib/ting_yun/agent/event/event_listener.rb +47 -0
  39. data/lib/ting_yun/agent/event/event_loop.rb +194 -0
  40. data/lib/ting_yun/agent/instance_methods/connect.rb +164 -0
  41. data/lib/ting_yun/agent/instance_methods/container_data_manager.rb +137 -0
  42. data/lib/ting_yun/agent/instance_methods/handle_errors.rb +71 -0
  43. data/lib/ting_yun/agent/instance_methods/start.rb +219 -0
  44. data/lib/ting_yun/agent/instance_methods/start_worker_thread.rb +51 -0
  45. data/lib/ting_yun/agent/instance_methods.rb +39 -0
  46. data/lib/ting_yun/agent/method_tracer.rb +256 -0
  47. data/lib/ting_yun/agent/method_tracer_helpers.rb +85 -0
  48. data/lib/ting_yun/agent/threading/agent_thread.rb +49 -0
  49. data/lib/ting_yun/agent/transaction/attributes.rb +22 -0
  50. data/lib/ting_yun/agent/transaction/request_attributes.rb +126 -0
  51. data/lib/ting_yun/agent/transaction/trace.rb +125 -0
  52. data/lib/ting_yun/agent/transaction/trace_node.rb +110 -0
  53. data/lib/ting_yun/agent/transaction/traced_method_stack.rb +80 -0
  54. data/lib/ting_yun/agent/transaction/transaction_metrics.rb +51 -0
  55. data/lib/ting_yun/agent/transaction/transaction_sample_builder.rb +63 -0
  56. data/lib/ting_yun/agent/transaction/transaction_state.rb +112 -0
  57. data/lib/ting_yun/agent/transaction.rb +522 -0
  58. data/lib/ting_yun/agent.rb +207 -0
  59. data/lib/ting_yun/configuration/default_source.rb +638 -0
  60. data/lib/ting_yun/configuration/dotted_hash.rb +46 -0
  61. data/lib/ting_yun/configuration/environment_source.rb +116 -0
  62. data/lib/ting_yun/configuration/manager.rb +232 -0
  63. data/lib/ting_yun/configuration/manual_source.rb +14 -0
  64. data/lib/ting_yun/configuration/server_source.rb +88 -0
  65. data/lib/ting_yun/configuration/yaml_source.rb +136 -0
  66. data/lib/ting_yun/configuration.rb +9 -0
  67. data/lib/ting_yun/environment_report.rb +123 -0
  68. data/lib/ting_yun/frameworks/class_methods.rb +47 -0
  69. data/lib/ting_yun/frameworks/external.rb +15 -0
  70. data/lib/ting_yun/frameworks/instance_methods.rb +120 -0
  71. data/lib/ting_yun/frameworks/instrumentation.rb +67 -0
  72. data/lib/ting_yun/frameworks/rails.rb +63 -0
  73. data/lib/ting_yun/frameworks/rails3.rb +26 -0
  74. data/lib/ting_yun/frameworks/rails4.rb +14 -0
  75. data/lib/ting_yun/frameworks/ruby.rb +17 -0
  76. data/lib/ting_yun/frameworks/sinatra.rb +10 -0
  77. data/lib/ting_yun/frameworks.rb +34 -0
  78. data/lib/ting_yun/http/generic_request.rb +8 -0
  79. data/lib/ting_yun/http/net_http_request.rb +46 -0
  80. data/lib/ting_yun/instrumentation/active_record.rb +103 -0
  81. data/lib/ting_yun/instrumentation/middleware_proxy.rb +77 -0
  82. data/lib/ting_yun/instrumentation/middleware_tracing.rb +84 -0
  83. data/lib/ting_yun/instrumentation/mongo.rb +103 -0
  84. data/lib/ting_yun/instrumentation/mongo2.rb +37 -0
  85. data/lib/ting_yun/instrumentation/mongo_command_log_subscriber.rb +97 -0
  86. data/lib/ting_yun/instrumentation/moped.rb +95 -0
  87. data/lib/ting_yun/instrumentation/net.rb +59 -0
  88. data/lib/ting_yun/instrumentation/rack.rb +109 -0
  89. data/lib/ting_yun/instrumentation/rails3/action_controller.rb +63 -0
  90. data/lib/ting_yun/instrumentation/rails3/action_view.rb +115 -0
  91. data/lib/ting_yun/instrumentation/rails4/action_controller_subscriber.rb +124 -0
  92. data/lib/ting_yun/instrumentation/rails4/action_view_subscriber.rb +118 -0
  93. data/lib/ting_yun/instrumentation/rails4/active_record_subscriber.rb +124 -0
  94. data/lib/ting_yun/instrumentation/rails_middleware.rb +38 -0
  95. data/lib/ting_yun/instrumentation/redis.rb +70 -0
  96. data/lib/ting_yun/instrumentation/support/active_record_helper.rb +178 -0
  97. data/lib/ting_yun/instrumentation/support/controller_instrumentation.rb +54 -0
  98. data/lib/ting_yun/instrumentation/support/database.rb +38 -0
  99. data/lib/ting_yun/instrumentation/support/event_formatter.rb +19 -0
  100. data/lib/ting_yun/instrumentation/support/evented_subscriber.rb +97 -0
  101. data/lib/ting_yun/instrumentation/support/external_error.rb +52 -0
  102. data/lib/ting_yun/instrumentation/support/metric_translator.rb +84 -0
  103. data/lib/ting_yun/instrumentation/support/mongo_formatter.rb +49 -0
  104. data/lib/ting_yun/instrumentation/support/parameter_filtering.rb +21 -0
  105. data/lib/ting_yun/instrumentation/support/queue_time.rb +76 -0
  106. data/lib/ting_yun/instrumentation/support/transaction_namer.rb +68 -0
  107. data/lib/ting_yun/instrumentation/thrift.rb +329 -0
  108. data/lib/ting_yun/logger/agent_logger.rb +196 -0
  109. data/lib/ting_yun/logger/log_once.rb +38 -0
  110. data/lib/ting_yun/logger/memory_logger.rb +56 -0
  111. data/lib/ting_yun/logger/null_logger.rb +31 -0
  112. data/lib/ting_yun/logger/startup_logger.rb +13 -0
  113. data/lib/ting_yun/logger.rb +8 -0
  114. data/lib/ting_yun/metrics/metric_data.rb +86 -0
  115. data/lib/ting_yun/metrics/metric_spec.rb +89 -0
  116. data/lib/ting_yun/metrics/stats.rb +158 -0
  117. data/lib/ting_yun/metrics.rb +12 -0
  118. data/lib/ting_yun/support/coerce.rb +86 -0
  119. data/lib/ting_yun/support/collector.rb +29 -0
  120. data/lib/ting_yun/support/exception.rb +79 -0
  121. data/lib/ting_yun/support/hash_extensions.rb +25 -0
  122. data/lib/ting_yun/support/helper.rb +54 -0
  123. data/lib/ting_yun/support/hostname.rb +13 -0
  124. data/lib/ting_yun/support/http_clients/uri_util.rb +49 -0
  125. data/lib/ting_yun/support/language_support.rb +155 -0
  126. data/lib/ting_yun/support/library_detection.rb +129 -0
  127. data/lib/ting_yun/support/local_environment.rb +185 -0
  128. data/lib/ting_yun/support/path.rb +13 -0
  129. data/lib/ting_yun/support/serialize/encodes.rb +61 -0
  130. data/lib/ting_yun/support/serialize/encoding_normalizer.rb +84 -0
  131. data/lib/ting_yun/support/serialize/json_marshaller.rb +73 -0
  132. data/lib/ting_yun/support/serialize/json_wrapper.rb +78 -0
  133. data/lib/ting_yun/support/serialize/marshaller.rb +69 -0
  134. data/lib/ting_yun/support/serialize/ok_json.rb +651 -0
  135. data/lib/ting_yun/support/system_info.rb +206 -0
  136. data/lib/ting_yun/support/timer_lib.rb +29 -0
  137. data/lib/ting_yun/support/version_number.rb +70 -0
  138. data/lib/ting_yun/ting_yun_service/connection.rb +118 -0
  139. data/lib/ting_yun/ting_yun_service/http.rb +41 -0
  140. data/lib/ting_yun/ting_yun_service/request.rb +90 -0
  141. data/lib/ting_yun/ting_yun_service/ssl.rb +45 -0
  142. data/lib/ting_yun/ting_yun_service/upload_service.rb +149 -0
  143. data/lib/ting_yun/ting_yun_service.rb +124 -0
  144. data/lib/ting_yun/version.rb +17 -0
  145. data/lib/tingyun_rpm.rb +47 -0
  146. data/tingyun_rpm.gemspec +60 -0
  147. metadata +415 -0
@@ -0,0 +1,410 @@
1
+ # encoding: utf-8
2
+
3
+ require 'ting_yun/support/helper'
4
+ module TingYun
5
+ module Agent
6
+ module Database
7
+
8
+ MAX_QUERY_LENGTH = 16384
9
+
10
+ extend self
11
+
12
+
13
+ def obfuscate_sql(sql)
14
+ Obfuscator.instance.obfuscator.call(sql)
15
+ end
16
+
17
+
18
+ def capture_query(query)
19
+ TingYun::Helper.correctly_encoded(truncate_query(query))
20
+ end
21
+
22
+ def truncate_query(query)
23
+ if query.length > (MAX_QUERY_LENGTH - 4)
24
+ query[0..MAX_QUERY_LENGTH - 4] + '...'
25
+ else
26
+ query
27
+ end
28
+ end
29
+
30
+
31
+ RECORD_FOR = [:raw, :obfuscated].freeze
32
+
33
+ def should_record_sql?(key)
34
+ RECORD_FOR.include?(record_sql_method(key.to_sym))
35
+ end
36
+
37
+ def record_sql_method(key)
38
+
39
+ case Agent.config[key].to_s
40
+ when 'off'
41
+ :off
42
+ when 'raw'
43
+ :raw
44
+ else
45
+ :obfuscated
46
+ end
47
+ end
48
+
49
+ def should_action_collect_explain_plans?
50
+ should_record_sql?("nbs.action_tracer.record_sql") &&
51
+ Agent.config["nbs.action_tracer.explain_enabled".to_sym]
52
+ end
53
+
54
+ def explain_sql(sql, config, explainer=nil)
55
+ return nil unless sql && explainer && config
56
+ _sql = sql.split(";\n")[0] # only explain the first
57
+ explain_plan = explain(_sql, config, explainer)
58
+ return explain_plan || {"dialect"=> nil, "keys"=>[], "values"=>[]}
59
+ end
60
+
61
+ SUPPORTED_ADAPTERS_FOR_EXPLAIN = %w[postgres postgresql mysql2 mysql sqlite].freeze
62
+
63
+ def explain(sql, config, explainer=nil)
64
+
65
+ return unless explainer && is_select?(sql)
66
+
67
+ if sql[-3,3] == '...'
68
+ TingYun::Agent.logger.debug('Unable to collect explain plan for truncated query.')
69
+ return
70
+ end
71
+
72
+ if parameterized?(sql)
73
+ TingYun::Agent.logger.debug('Unable to collect explain plan for parameterized query.')
74
+ return
75
+ end
76
+
77
+ adapter = adapter_from_config(config)
78
+ if !SUPPORTED_ADAPTERS_FOR_EXPLAIN.include?(adapter)
79
+ TingYun::Agent.logger.debug("Not collecting explain plan because an unknown connection adapter ('#{adapter}') was used.")
80
+ return
81
+ end
82
+
83
+ handle_exception_in_explain do
84
+ plan = explainer.call(config, sql)
85
+ return process_resultset(plan, adapter) if plan
86
+ end
87
+ end
88
+
89
+ def adapter_from_config(config)
90
+ if config[:adapter]
91
+ return config[:adapter].to_s
92
+ elsif config[:uri] && config[:uri].to_s =~ /^jdbc:([^:]+):/
93
+ # This case is for Sequel with the jdbc-mysql, jdbc-postgres, or
94
+ # jdbc-sqlite3 gems.
95
+ return $1
96
+ end
97
+ end
98
+
99
+
100
+ def parameterized?(sql)
101
+ Obfuscator.instance.obfuscate_single_quote_literals(sql) =~ /\$\d+/
102
+ end
103
+
104
+ def is_select?(sql)
105
+ parse_operation_from_query(sql) == 'select'
106
+ end
107
+
108
+ def process_resultset(results ,adapter)
109
+ case adapter.to_s
110
+ when 'postgres', 'postgresql'
111
+ process_explain_results_postgres(results)
112
+ when 'mysql2'
113
+ process_explain_results_mysql2(results)
114
+ when 'mysql'
115
+ process_explain_results_mysql(results)
116
+ when 'sqlite'
117
+ process_explain_results_sqlite(results)
118
+ end
119
+ end
120
+
121
+ QUERY_PLAN = 'QUERY PLAN'.freeze
122
+
123
+ def process_explain_results_postgres(results)
124
+ if results.is_a?(String)
125
+ query_plan_string = results
126
+ else
127
+ lines = []
128
+ results.each { |row| lines << row[QUERY_PLAN] }
129
+ query_plan_string = lines.join("\n")
130
+ end
131
+
132
+ unless record_sql_method == :raw
133
+ query_plan_string = Obfuscator.instance.obfuscate_postgres_explain(query_plan_string)
134
+ end
135
+ values = query_plan_string.split("\n").map { |line| [line] }
136
+
137
+ {"dialect"=> "PostgreSQL", "keys"=>[QUERY_PLAN], "values"=>values}
138
+ end
139
+
140
+ def string_explain_plan_results(adpater, results)
141
+ {"dialect"=> adpater, "keys"=>[], "values"=>[results]}
142
+ end
143
+
144
+ def process_explain_results_mysql2(results)
145
+ return string_explain_plan_results("MySQL", results) if results.is_a?(String)
146
+ headers = results.fields
147
+ values = []
148
+ results.each { |row| values << row }
149
+ {"dialect"=> "MySQL", "keys"=>headers, "values"=>values}
150
+ end
151
+
152
+ def process_explain_results_mysql(results)
153
+ return string_explain_plan_results("MySQL", results) if results.is_a?(String)
154
+ headers = []
155
+ values = []
156
+ if results.is_a?(Array)
157
+ # We're probably using the jdbc-mysql gem for JRuby, which will give
158
+ # us an array of hashes.
159
+ headers = results.first.keys
160
+ results.each do |row|
161
+ values << headers.map { |h| row[h] }
162
+ end
163
+ else
164
+ # We're probably using the native mysql driver gem, which will give us
165
+ # a Mysql::Result object that responds to each_hash
166
+ results.each_hash do |row|
167
+ headers = row.keys
168
+ values << headers.map { |h| row[h] }
169
+ end
170
+ end
171
+ {"dialect"=> "MySQL", "keys"=>headers, "values"=>values}
172
+ end
173
+
174
+ SQLITE_EXPLAIN_COLUMNS = %w[addr opcode p1 p2 p3 p4 p5 comment]
175
+
176
+ def process_explain_results_sqlite(results)
177
+ return string_explain_plan_results("sqlite", results) if results.is_a?(String)
178
+ headers = SQLITE_EXPLAIN_COLUMNS
179
+ values = []
180
+ results.each do |row|
181
+ values << headers.map { |h| row[h] }
182
+ end
183
+ {"dialect"=> "sqlite", "keys"=>headers, "values"=>values}
184
+ end
185
+
186
+
187
+
188
+ KNOWN_OPERATIONS = [
189
+ 'alter',
190
+ 'select',
191
+ 'update',
192
+ 'delete',
193
+ 'insert',
194
+ 'create',
195
+ 'show',
196
+ 'set',
197
+ 'exec',
198
+ 'execute',
199
+ 'call'
200
+ ]
201
+
202
+ SQL_COMMENT_REGEX = Regexp.new('/\*.*?\*/', Regexp::MULTILINE).freeze
203
+ EMPTY_STRING = ''.freeze
204
+
205
+ def parse_operation_from_query(sql)
206
+ sql = TingYun::Helper.correctly_encoded(sql).gsub(SQL_COMMENT_REGEX, EMPTY_STRING)
207
+ if sql =~ /(\w+)/
208
+ op = $1.downcase
209
+ return op if KNOWN_OPERATIONS.include?(op)
210
+ end
211
+ end
212
+
213
+
214
+ def handle_exception_in_explain
215
+ yield
216
+ rescue => e
217
+ ::TingYun::Agent.logger.error("Error getting query plan:", e)
218
+ nil
219
+ end
220
+
221
+
222
+ def get_connection(config, &connector)
223
+ ConnectionManager.instance.get_connection(config, &connector)
224
+ end
225
+
226
+ def close_connections
227
+ ConnectionManager.instance.close_connections
228
+ end
229
+
230
+ # Returns a cached connection for a given ActiveRecord
231
+ # configuration - these are stored or reopened as needed, and if
232
+ # we cannot get one, we ignore it and move on without explaining
233
+ # the sql
234
+ class ConnectionManager
235
+ include Singleton
236
+
237
+ def get_connection(config, &connector)
238
+ @connections ||= {}
239
+
240
+ connection = @connections[config]
241
+
242
+ return connection if connection
243
+
244
+ begin
245
+ @connections[config] = connector.call(config)
246
+ rescue => e
247
+ ::TingYun::Agent.logger.error("Caught exception trying to get connection to DB for explain.", e)
248
+ nil
249
+ end
250
+ end
251
+
252
+ # Closes all the connections in the internal connection cache
253
+ def close_connections
254
+ @connections ||= {}
255
+ @connections.values.each do |connection|
256
+ begin
257
+ connection.disconnect!
258
+ rescue
259
+ end
260
+ end
261
+
262
+ @connections = {}
263
+ end
264
+ end
265
+
266
+ class Statement
267
+ attr_accessor :sql, :config, :explainer
268
+
269
+ def initialize(sql, config={}, explainer=nil)
270
+ @sql = TingYun::Agent::Database.capture_query(sql)
271
+ @config = config
272
+ @explainer = explainer
273
+ end
274
+
275
+ def adapter
276
+ config && config[:adapter]
277
+ end
278
+ end
279
+
280
+ #混淆器
281
+ class Obfuscator
282
+ include Singleton
283
+
284
+ attr_reader :obfuscator
285
+
286
+ def initialize
287
+ reset
288
+ end
289
+
290
+ def reset
291
+ @obfuscator = method(:default_sql_obfuscator)
292
+ end
293
+
294
+ QUERY_TOO_LARGE_MESSAGE = "Query too large (over 16k characters) to safely obfuscate"
295
+ FAILED_TO_OBFUSCATE_MESSAGE = "Failed to obfuscate SQL query - quote characters remained after obfuscation"
296
+
297
+ def default_sql_obfuscator(sql)
298
+ stmt = sql.kind_of?(Statement) ? sql : Statement.new(sql)
299
+
300
+ if stmt.sql[-3,3] == '...'
301
+ return QUERY_TOO_LARGE_MESSAGE
302
+ end
303
+
304
+ obfuscate_double_quotes = stmt.adapter.to_s !~ /postgres|sqlite/
305
+
306
+ obfuscated = obfuscate_numeric_literals(stmt.sql)
307
+
308
+ if obfuscate_double_quotes
309
+ obfuscated = obfuscate_quoted_literals(obfuscated)
310
+ obfuscated = remove_comments(obfuscated)
311
+ if contains_quotes?(obfuscated)
312
+ obfuscated = FAILED_TO_OBFUSCATE_MESSAGE
313
+ end
314
+ else
315
+ obfuscated = obfuscate_single_quote_literals(obfuscated)
316
+ obfuscated = remove_comments(obfuscated)
317
+ if contains_single_quotes?(obfuscated)
318
+ obfuscated = FAILED_TO_OBFUSCATE_MESSAGE
319
+ end
320
+ end
321
+
322
+
323
+ obfuscated.to_s # return back to a regular String
324
+ end
325
+
326
+ QUOTED_STRINGS_REGEX = /'(?:[^']|'')*'|"(?:[^"]|"")*"/
327
+ LABEL_LINE_REGEX = /^([^:\n]*:\s+).*$/.freeze
328
+
329
+ def obfuscate_postgres_explain(explain)
330
+ explain.gsub!(QUOTED_STRINGS_REGEX) do |match|
331
+ match.start_with?('"') ? match : '?'
332
+ end
333
+ explain.gsub!(LABEL_LINE_REGEX, '\1?')
334
+ explain
335
+ end
336
+
337
+ module ObfuscationHelpers
338
+ # Note that the following two regexes are applied to a reversed version
339
+ # of the query. This is why the backslash escape sequences (\' and \")
340
+ # appear reversed within them.
341
+ #
342
+ # Note that some database adapters (notably, PostgreSQL with
343
+ # standard_conforming_strings on and MySQL with NO_BACKSLASH_ESCAPES on)
344
+ # do not apply special treatment to backslashes within quoted string
345
+ # literals. We don't have an easy way of determining whether the
346
+ # database connection from which a query was captured was operating in
347
+ # one of these modes, but the obfuscation is done in such a way that it
348
+ # should not matter.
349
+ #
350
+ # Reversing the query string before obfuscation allows us to get around
351
+ # the fact that a \' appearing within a string may or may not terminate
352
+ # the string, because we know that a string cannot *start* with a \'.
353
+ REVERSE_SINGLE_QUOTES_REGEX = /'(?:''|'\\|[^'])*'/
354
+ REVERSE_ANY_QUOTES_REGEX = /'(?:''|'\\|[^'])*'|"(?:""|"\\|[^"])*"/
355
+
356
+ NUMERICS_REGEX = /\b\d+\b/
357
+
358
+ # We take a conservative, overly-aggressive approach to obfuscating
359
+ # comments, and drop everything from the query after encountering any
360
+ # character sequence that could be a comment initiator. We do this after
361
+ # removal of string literals to avoid accidentally over-obfuscating when
362
+ # a string literal contains a comment initiator.
363
+ SQL_COMMENT_REGEX = Regexp.new('(?:/\*|--|#).*', Regexp::MULTILINE).freeze
364
+
365
+ # We use these to check whether the query contains any quote characters
366
+ # after obfuscation. If so, that's a good indication that the original
367
+ # query was malformed, and so our obfuscation can't reliabily find
368
+ # literals. In such a case, we'll replace the entire query with a
369
+ # placeholder.
370
+ LITERAL_SINGLE_QUOTE = "'".freeze
371
+ LITERAL_DOUBLE_QUOTE = '"'.freeze
372
+
373
+ PLACEHOLDER = '?'.freeze
374
+
375
+ def obfuscate_single_quote_literals(sql)
376
+ obfuscated = sql.reverse
377
+ obfuscated.gsub!(REVERSE_SINGLE_QUOTES_REGEX, PLACEHOLDER)
378
+ obfuscated.reverse!
379
+ obfuscated
380
+ end
381
+
382
+ def obfuscate_quoted_literals(sql)
383
+ obfuscated = sql.reverse
384
+ obfuscated.gsub!(REVERSE_ANY_QUOTES_REGEX, PLACEHOLDER)
385
+ obfuscated.reverse!
386
+ obfuscated
387
+ end
388
+
389
+ def obfuscate_numeric_literals(sql)
390
+ sql.gsub(NUMERICS_REGEX, PLACEHOLDER)
391
+ end
392
+
393
+ def remove_comments(sql)
394
+ sql.gsub(SQL_COMMENT_REGEX, PLACEHOLDER)
395
+ end
396
+
397
+ def contains_single_quotes?(str)
398
+ str.include?(LITERAL_SINGLE_QUOTE)
399
+ end
400
+
401
+ def contains_quotes?(str)
402
+ str.include?(LITERAL_SINGLE_QUOTE) || str.include?(LITERAL_DOUBLE_QUOTE)
403
+ end
404
+ end
405
+ include ObfuscationHelpers
406
+ end
407
+
408
+ end
409
+ end
410
+ end
@@ -0,0 +1,82 @@
1
+ # encoding: utf-8
2
+ require 'ting_yun/agent/transaction/transaction_state'
3
+ module TingYun
4
+ module Agent
5
+ module Datastore
6
+ module MetricHelper
7
+
8
+
9
+ ALL_WEB = "AllWeb".freeze
10
+ ALL_BACKGROUND = "AllBackground".freeze
11
+ ALL = "All".freeze
12
+
13
+ NOSQL = %w(MongoDB Redis Memcached).freeze
14
+
15
+ def self.checkNosql(product)
16
+ NOSQL.include?(product)
17
+ end
18
+
19
+ def self.metric_name(product, collection, operation)
20
+ if checkNosql(product)
21
+ if product == 'MongoDB'
22
+ "#{product}/#{collection}/#{operation}"
23
+ else
24
+ "#{product}/NULL/#{operation}"
25
+ end
26
+ else
27
+ "Database #{product}/#{collection}/#{operation}"
28
+ end
29
+ end
30
+
31
+ def self.product_suffixed_rollup(product,suffix)
32
+ if checkNosql(product)
33
+ "#{product}/NULL/#{suffix}"
34
+ else
35
+ "Database #{product}/NULL/#{suffix}"
36
+ end
37
+ end
38
+
39
+
40
+
41
+ def self.metrics_for(product, operation, collection = nil, generic_product = nil)
42
+ operation = operation.to_s.upcase
43
+ if overrides = overridden_operation_and_collection # [method, model_name, product]
44
+ if should_override?(overrides, product, generic_product)
45
+ operation = overrides[0] || operation
46
+ collection = overrides[1] || collection
47
+ end
48
+ end
49
+ metrics = [ALL_WEB,ALL]
50
+ metrics << operation
51
+ metrics = metrics.map do |suffix|
52
+ product_suffixed_rollup(product,suffix)
53
+ end
54
+
55
+ metrics.unshift metric_name(product, collection, operation)
56
+ metrics
57
+ end
58
+
59
+ # Allow Transaction#with_database_metric_name to override our
60
+ # collection and operation
61
+ def self.overridden_operation_and_collection #THREAD_LOCAL_ACCESS
62
+ state = TingYun::Agent::TransactionState.tl_get
63
+ txn = state.current_transaction
64
+ txn ? txn.instrumentation_state[:datastore_override] : nil
65
+ end
66
+
67
+ # If the override declared a product affiliation, abide by that
68
+ # ActiveRecord has database-specific product names, so we recognize
69
+ # it by the generic_product it passes.
70
+ def self.should_override?(overrides, product, generic_product)
71
+ override_product = overrides[2]
72
+
73
+ override_product.nil? ||
74
+ override_product == product ||
75
+ override_product == generic_product
76
+ end
77
+
78
+ end
79
+ end
80
+ end
81
+ end
82
+
@@ -0,0 +1,44 @@
1
+ # encoding: utf-8
2
+ require 'ting_yun/support/version_number'
3
+ module TingYun
4
+ module Agent
5
+ module Datastore
6
+ module Mongo
7
+
8
+ def self.monitoring_enabled?
9
+ defined?(::Mongo::Monitoring)
10
+ end
11
+
12
+ def self.version_1_10_or_later?
13
+ # Again, no VERSION constant in 1.x, so we have to rely on constant checks
14
+ defined?(::Mongo::CollectionOperationWriter)
15
+ end
16
+
17
+ def self.unsupported_2x?
18
+ defined?(::Mongo::VERSION) && TingYun::Support::VersionNumber.new(::Mongo::VERSION).major_version == 2
19
+ end
20
+
21
+ def self.supported_version?
22
+ # No version constant in < 2.0 versions of Mongo :(
23
+ defined?(::Mongo) && (defined?(::Mongo::MongoClient) || monitoring_enabled?)
24
+ end
25
+
26
+ # def self.transform_operation(operation)
27
+ # t_operation = case operation.to_s.upcase
28
+ # when 'DELETE', 'FIND_AND_REMOVE', 'DELETEINDEXS', 'REMOVE' then 'destroy'
29
+ # when 'INSERT' then 'INSERT'
30
+ # when 'UPDATE', 'RENAMECOLLECTION', 'REINDEX' then 'UPDATE'
31
+ # when 'CREATE', 'FIND_AND_MODIFY', 'CREATEINDEXS', 'CREATEINDEX', 'REPINDEX' then 'SAVE'
32
+ # when 'QUERY', 'COUNT', 'GET_MORE', 'AGGREGATE', 'FIND', 'FINDONE', 'GROUP' then 'SECECT'
33
+ # else
34
+ # nil
35
+ # end
36
+ # t_operation
37
+ # end
38
+ def self.transform_operation(operation)
39
+ operation.to_s.upcase
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,33 @@
1
+ # encoding: utf-8
2
+
3
+ require 'ting_yun/agent/datastore/metric_helper'
4
+ require 'ting_yun/agent/method_tracer'
5
+
6
+
7
+ module TingYun
8
+ module Agent
9
+ module Datastore
10
+
11
+
12
+ def self.wrap(product, operation, collection = nil, callback = nil)
13
+ return yield unless operation
14
+
15
+ metrics = TingYun::Agent::Datastore::MetricHelper.metrics_for(product, operation, collection)
16
+
17
+ scoped_metric = metrics.last
18
+
19
+ TingYun::Agent::MethodTracer.trace_execution_scoped(metrics) do
20
+ t0 = Time.now
21
+ begin
22
+ result = yield
23
+ ensure
24
+ elapsed_time = (Time.now - t0).to_f
25
+ if callback
26
+ callback.call(result, scoped_metric, elapsed_time)
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,39 @@
1
+ # encoding: utf-8
2
+
3
+ module TingYun
4
+ module Agent
5
+ class Dispatcher
6
+ attr_accessor :starting_pid
7
+
8
+ def initialize(events, after_forker=TingYun::Agent)
9
+ # We intentionally don't set our pid as started at this point.
10
+ # Startup routines must call mark_started when they consider us set!
11
+ @starting_pid = nil
12
+ @after_forker = after_forker
13
+
14
+ if events
15
+ events.subscribe(:start_transaction, &method(:on_transaction))
16
+ end
17
+ end
18
+
19
+ def on_transaction(*_)
20
+ return unless needs_restart?
21
+
22
+ restart_harvest_thread
23
+ end
24
+
25
+ def mark_started(pid = Process.pid)
26
+ @starting_pid = pid
27
+ end
28
+
29
+ def needs_restart?(pid = Process.pid)
30
+ @starting_pid != pid
31
+ end
32
+
33
+ def restart_harvest_thread
34
+ @after_forker.after_fork(:force_reconnect => true)
35
+ end
36
+
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,47 @@
1
+ # encoding: utf-8
2
+
3
+ module TingYun
4
+ module Agent
5
+ module Event
6
+ class EventListener
7
+
8
+ attr_accessor :allocation
9
+
10
+ def initialize
11
+ @events = {}
12
+ @allocation = 100
13
+ end
14
+
15
+ def subscribe(event, &handler)
16
+ @events[event] ||= []
17
+ @events[event] << handler
18
+ check_allocation(event)
19
+ end
20
+
21
+ def check_allocation(event)
22
+ if @events[event].size > @allocation
23
+ TingYun::Agent.logger.debug("Run-away event subscription on #{event}? Subscribed #{count}")
24
+ end
25
+ end
26
+
27
+ def clear
28
+ @events.clear
29
+ end
30
+
31
+
32
+ def notify(event, *args)
33
+ return unless @events.has_key?(event)
34
+
35
+ @events[event].each do |handler|
36
+ begin
37
+ handler.call(*args)
38
+ rescue => err
39
+ TingYun::Agent.logger.debug("Failure during notify for #{event}", err)
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
47
+