whatap-python 2.1.0__py3-none-any.whl

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.
Files changed (227) hide show
  1. whatap/LICENSE +0 -0
  2. whatap/README.rst +49 -0
  3. whatap/__init__.py +923 -0
  4. whatap/__main__.py +4 -0
  5. whatap/agent/darwin/amd64/whatap_python +0 -0
  6. whatap/agent/darwin/arm64/whatap_python +0 -0
  7. whatap/agent/linux/amd64/whatap_python +0 -0
  8. whatap/agent/linux/arm64/whatap_python +0 -0
  9. whatap/agent/windows/whatap_python.exe +0 -0
  10. whatap/bootstrap/__init__.py +0 -0
  11. whatap/bootstrap/sitecustomize.py +19 -0
  12. whatap/build.py +4 -0
  13. whatap/conf/__init__.py +0 -0
  14. whatap/conf/configuration.py +280 -0
  15. whatap/conf/configure.py +105 -0
  16. whatap/conf/license.py +49 -0
  17. whatap/control/__init__.py +0 -0
  18. whatap/counter/__init__.py +14 -0
  19. whatap/counter/counter_manager.py +45 -0
  20. whatap/counter/tasks/__init__.py +3 -0
  21. whatap/counter/tasks/base_task.py +26 -0
  22. whatap/counter/tasks/llm_evaluator_task.py +501 -0
  23. whatap/counter/tasks/llm_log_sink_task.py +309 -0
  24. whatap/counter/tasks/llm_stat_task.py +78 -0
  25. whatap/counter/tasks/openfiledescriptor.py +67 -0
  26. whatap/io/__init__.py +1 -0
  27. whatap/io/data_inputx.py +161 -0
  28. whatap/io/data_outputx.py +262 -0
  29. whatap/llm/__init__.py +17 -0
  30. whatap/llm/definitions.py +43 -0
  31. whatap/llm/evaluators/__init__.py +136 -0
  32. whatap/llm/evaluators/base.py +114 -0
  33. whatap/llm/evaluators/builtins/__init__.py +91 -0
  34. whatap/llm/evaluators/builtins/answer_relevance.py +46 -0
  35. whatap/llm/evaluators/builtins/combined_judge.py +271 -0
  36. whatap/llm/evaluators/builtins/factuality.py +71 -0
  37. whatap/llm/evaluators/builtins/hallucination.py +97 -0
  38. whatap/llm/evaluators/builtins/llm_judge.py +516 -0
  39. whatap/llm/evaluators/builtins/pii_leak.py +214 -0
  40. whatap/llm/evaluators/builtins/prompt_injection.py +71 -0
  41. whatap/llm/evaluators/builtins/toxicity.py +53 -0
  42. whatap/llm/evaluators/builtins/url_scan.py +194 -0
  43. whatap/llm/evaluators/registry.py +192 -0
  44. whatap/llm/evaluators/sampler.py +83 -0
  45. whatap/llm/evaluators/scope.py +334 -0
  46. whatap/llm/features.py +66 -0
  47. whatap/llm/log_sink_packs/__init__.py +9 -0
  48. whatap/llm/log_sink_packs/llm_input_message.py +16 -0
  49. whatap/llm/log_sink_packs/llm_log_sink_pack.py +72 -0
  50. whatap/llm/log_sink_packs/llm_output_message.py +19 -0
  51. whatap/llm/log_sink_packs/llm_step_eval_status.py +94 -0
  52. whatap/llm/log_sink_packs/llm_step_status.py +118 -0
  53. whatap/llm/log_sink_packs/llm_system_message.py +16 -0
  54. whatap/llm/log_sink_packs/llm_tool_calls.py +44 -0
  55. whatap/llm/log_sink_packs/llm_tool_results.py +16 -0
  56. whatap/llm/log_sink_packs/llm_tx_status.py +108 -0
  57. whatap/llm/pricing.py +236 -0
  58. whatap/llm/prompt_meta.py +288 -0
  59. whatap/llm/providers/__init__.py +0 -0
  60. whatap/llm/providers/anthropic/__init__.py +37 -0
  61. whatap/llm/providers/anthropic/messages/__init__.py +0 -0
  62. whatap/llm/providers/anthropic/messages/messages.py +70 -0
  63. whatap/llm/providers/anthropic/messages/messages_context.py +76 -0
  64. whatap/llm/providers/anthropic/messages/messages_extractor.py +126 -0
  65. whatap/llm/providers/interceptor.py +182 -0
  66. whatap/llm/providers/openai/__init__.py +133 -0
  67. whatap/llm/providers/openai/chat/__init__.py +0 -0
  68. whatap/llm/providers/openai/chat/chat.py +82 -0
  69. whatap/llm/providers/openai/chat/chat_context.py +78 -0
  70. whatap/llm/providers/openai/chat/chat_extractor.py +127 -0
  71. whatap/llm/providers/openai/completions/__init__.py +0 -0
  72. whatap/llm/providers/openai/completions/completions.py +70 -0
  73. whatap/llm/providers/openai/completions/completions_context.py +31 -0
  74. whatap/llm/providers/openai/completions/completions_extractor.py +61 -0
  75. whatap/llm/providers/openai/content_parser.py +41 -0
  76. whatap/llm/providers/openai/embeddings/__init__.py +0 -0
  77. whatap/llm/providers/openai/embeddings/embeddings.py +59 -0
  78. whatap/llm/providers/openai/embeddings/embeddings_context.py +25 -0
  79. whatap/llm/providers/openai/embeddings/embeddings_extractor.py +26 -0
  80. whatap/llm/providers/openai/responses/__init__.py +0 -0
  81. whatap/llm/providers/openai/responses/responses.py +70 -0
  82. whatap/llm/providers/openai/responses/responses_context.py +88 -0
  83. whatap/llm/providers/openai/responses/responses_extractor.py +126 -0
  84. whatap/llm/providers/stream_accumulator.py +73 -0
  85. whatap/llm/stats/__init__.py +35 -0
  86. whatap/llm/stats/active_stat.py +86 -0
  87. whatap/llm/stats/answer_relevance_eval_stat.py +10 -0
  88. whatap/llm/stats/api_status_stat.py +35 -0
  89. whatap/llm/stats/base_stat.py +107 -0
  90. whatap/llm/stats/combined_judge_eval_stat.py +11 -0
  91. whatap/llm/stats/error_stat.py +59 -0
  92. whatap/llm/stats/eval_stat.py +225 -0
  93. whatap/llm/stats/factuality_eval_stat.py +10 -0
  94. whatap/llm/stats/feature_stat.py +104 -0
  95. whatap/llm/stats/finish_stat.py +105 -0
  96. whatap/llm/stats/hallucination_eval_stat.py +10 -0
  97. whatap/llm/stats/meter.py +18 -0
  98. whatap/llm/stats/perf_stat.py +117 -0
  99. whatap/llm/stats/pii_leak_eval_stat.py +12 -0
  100. whatap/llm/stats/prompt_injection_eval_stat.py +10 -0
  101. whatap/llm/stats/token_usage_stat.py +133 -0
  102. whatap/llm/stats/toxicity_eval_stat.py +10 -0
  103. whatap/llm/stats/url_scan_eval_stat.py +12 -0
  104. whatap/net/__init__.py +0 -0
  105. whatap/net/async_sender.py +107 -0
  106. whatap/net/packet_enum.py +44 -0
  107. whatap/net/packet_type_enum.py +31 -0
  108. whatap/net/param_def.py +69 -0
  109. whatap/net/stackhelper.py +87 -0
  110. whatap/net/udp_session.py +394 -0
  111. whatap/net/udp_thread.py +54 -0
  112. whatap/pack/__init__.py +0 -0
  113. whatap/pack/logSinkPack.py +77 -0
  114. whatap/pack/pack.py +34 -0
  115. whatap/pack/pack_enum.py +41 -0
  116. whatap/pack/tagCountPack.py +61 -0
  117. whatap/scripts/__init__.py +208 -0
  118. whatap/trace/__init__.py +12 -0
  119. whatap/trace/mod/__init__.py +0 -0
  120. whatap/trace/mod/amqp/__init__.py +0 -0
  121. whatap/trace/mod/amqp/kombu.py +122 -0
  122. whatap/trace/mod/amqp/pika.py +62 -0
  123. whatap/trace/mod/application/__init__.py +0 -0
  124. whatap/trace/mod/application/bottle.py +34 -0
  125. whatap/trace/mod/application/celery.py +81 -0
  126. whatap/trace/mod/application/cherrypy.py +30 -0
  127. whatap/trace/mod/application/django.py +287 -0
  128. whatap/trace/mod/application/django_asgi.py +266 -0
  129. whatap/trace/mod/application/django_py3.py +251 -0
  130. whatap/trace/mod/application/fastapi/__init__.py +31 -0
  131. whatap/trace/mod/application/fastapi/endpoint.py +73 -0
  132. whatap/trace/mod/application/fastapi/exception_log.py +63 -0
  133. whatap/trace/mod/application/fastapi/instrumentation.py +204 -0
  134. whatap/trace/mod/application/fastapi/scope.py +115 -0
  135. whatap/trace/mod/application/fastapi/transaction.py +67 -0
  136. whatap/trace/mod/application/flask.py +52 -0
  137. whatap/trace/mod/application/frappe.py +224 -0
  138. whatap/trace/mod/application/graphql.py +170 -0
  139. whatap/trace/mod/application/nameko.py +39 -0
  140. whatap/trace/mod/application/odoo.py +63 -0
  141. whatap/trace/mod/application/starlette.py +126 -0
  142. whatap/trace/mod/application/tornado.py +163 -0
  143. whatap/trace/mod/application/wsgi.py +195 -0
  144. whatap/trace/mod/database/__init__.py +0 -0
  145. whatap/trace/mod/database/cxoracle.py +49 -0
  146. whatap/trace/mod/database/mongo.py +169 -0
  147. whatap/trace/mod/database/mysql.py +80 -0
  148. whatap/trace/mod/database/neo4j.py +90 -0
  149. whatap/trace/mod/database/psycopg2.py +45 -0
  150. whatap/trace/mod/database/psycopg3.py +359 -0
  151. whatap/trace/mod/database/redis.py +122 -0
  152. whatap/trace/mod/database/sqlalchemy.py +213 -0
  153. whatap/trace/mod/database/sqlite3.py +130 -0
  154. whatap/trace/mod/database/util.py +630 -0
  155. whatap/trace/mod/email/__init__.py +0 -0
  156. whatap/trace/mod/email/smtp.py +78 -0
  157. whatap/trace/mod/httpc/__init__.py +0 -0
  158. whatap/trace/mod/httpc/django.py +31 -0
  159. whatap/trace/mod/httpc/httplib.py +70 -0
  160. whatap/trace/mod/httpc/httpx.py +62 -0
  161. whatap/trace/mod/httpc/requests.py +20 -0
  162. whatap/trace/mod/httpc/urllib3.py +27 -0
  163. whatap/trace/mod/httpc/util.py +388 -0
  164. whatap/trace/mod/logging.py +161 -0
  165. whatap/trace/mod/plugin.py +84 -0
  166. whatap/trace/mod/standalone/__init__.py +0 -0
  167. whatap/trace/mod/standalone/multiple.py +293 -0
  168. whatap/trace/mod/standalone/single.py +135 -0
  169. whatap/trace/simple_trace_context.py +18 -0
  170. whatap/trace/trace_context.py +212 -0
  171. whatap/trace/trace_context_manager.py +244 -0
  172. whatap/trace/trace_error.py +84 -0
  173. whatap/trace/trace_handler.py +89 -0
  174. whatap/trace/trace_import.py +91 -0
  175. whatap/trace/trace_module_definition.py +156 -0
  176. whatap/util/__init__.py +0 -0
  177. whatap/util/bit_util.py +49 -0
  178. whatap/util/cardinality/__init__.py +0 -0
  179. whatap/util/cardinality/hyperloglog.py +84 -0
  180. whatap/util/cardinality/murmurhash.py +20 -0
  181. whatap/util/cardinality/registerset.py +60 -0
  182. whatap/util/compare_util.py +19 -0
  183. whatap/util/date_util.py +55 -0
  184. whatap/util/debug_util.py +73 -0
  185. whatap/util/escape_literal_sql.py +233 -0
  186. whatap/util/frame_util.py +20 -0
  187. whatap/util/hash_util.py +103 -0
  188. whatap/util/hexa32.py +66 -0
  189. whatap/util/int_set.py +199 -0
  190. whatap/util/ip_util.py +63 -0
  191. whatap/util/keygen.py +11 -0
  192. whatap/util/linked_list.py +113 -0
  193. whatap/util/linked_map.py +359 -0
  194. whatap/util/metering_util.py +103 -0
  195. whatap/util/request_double_queue.py +68 -0
  196. whatap/util/request_queue.py +60 -0
  197. whatap/util/string_util.py +20 -0
  198. whatap/util/throttle_util.py +99 -0
  199. whatap/util/userid_util.py +134 -0
  200. whatap/value/__init__.py +1 -0
  201. whatap/value/blob_value.py +38 -0
  202. whatap/value/boolean_value.py +33 -0
  203. whatap/value/decimal_value.py +36 -0
  204. whatap/value/double_summary.py +86 -0
  205. whatap/value/double_value.py +33 -0
  206. whatap/value/float_array.py +42 -0
  207. whatap/value/float_value.py +34 -0
  208. whatap/value/int_array.py +42 -0
  209. whatap/value/ip4_value.py +50 -0
  210. whatap/value/list_value.py +105 -0
  211. whatap/value/long_array.py +44 -0
  212. whatap/value/long_summary.py +83 -0
  213. whatap/value/map_value.py +154 -0
  214. whatap/value/null_value.py +21 -0
  215. whatap/value/number_value.py +33 -0
  216. whatap/value/summary_value.py +39 -0
  217. whatap/value/text_array.py +58 -0
  218. whatap/value/text_hash_value.py +37 -0
  219. whatap/value/text_value.py +43 -0
  220. whatap/value/value.py +26 -0
  221. whatap/value/value_enum.py +80 -0
  222. whatap/whatap.conf +14 -0
  223. whatap_python-2.1.0.dist-info/METADATA +87 -0
  224. whatap_python-2.1.0.dist-info/RECORD +227 -0
  225. whatap_python-2.1.0.dist-info/WHEEL +5 -0
  226. whatap_python-2.1.0.dist-info/entry_points.txt +6 -0
  227. whatap_python-2.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,208 @@
1
+ import os
2
+ import re
3
+ import time
4
+ from functools import wraps
5
+
6
+ import sys, threading
7
+
8
+ from whatap import check_whatap_home, ROOT_DIR, init_config, update_config, \
9
+ batch_agent, AGENT_NAME, go, configPort, configLlmPort, preview_whatap_conf
10
+
11
+
12
+ def whatap_command(func):
13
+ @wraps(func)
14
+ def wrapper(*args, **kwargs):
15
+ if len(sys.argv) == 1:
16
+ print('WHATAP: INVALID ARGMENTS.')
17
+ print(func.__doc__)
18
+ else:
19
+ if check_whatap_home():
20
+ return func(*args, **kwargs)
21
+
22
+ return wrapper
23
+
24
+ def start_agent_batch():
25
+ batch_agent()
26
+
27
+ def stop_agent():
28
+ try:
29
+ if sys.platform == 'win32':
30
+ # Windows: use taskkill command
31
+ os.system('taskkill /F /IM {}.exe'.format(AGENT_NAME))
32
+ else:
33
+ # Unix/Linux: use killall command
34
+ os.system('killall {}'.format(AGENT_NAME))
35
+ except Exception as e:
36
+ if sys.platform == 'win32':
37
+ print('Try to execute command: tasklist | findstr {}'.format(AGENT_NAME))
38
+ print('Next, taskkill /F /IM {}.exe'.format(AGENT_NAME))
39
+ else:
40
+ print(
41
+ 'Try to execute command. \n {}'.format(
42
+ '`ps -ef | grep {}`'.format(AGENT_NAME)))
43
+ print(
44
+ 'Next, `sudo killall {}`'.format(AGENT_NAME))
45
+ finally:
46
+ print('WHATAP: AGENT STOP.')
47
+
48
+ @whatap_command
49
+ def start_agent():
50
+ """
51
+ Usage:
52
+ whatap-start-agent [YOUR_APPLICATION_START_COMMAND]
53
+ """
54
+
55
+ args = sys.argv[1:]
56
+ root_directory = os.path.dirname(ROOT_DIR)
57
+ boot_directory = os.path.join(root_directory, 'bootstrap')
58
+
59
+ python_path = boot_directory
60
+
61
+ if 'PYTHONPATH' in os.environ:
62
+ path = os.environ['PYTHONPATH'].split(os.path.pathsep)
63
+ if not boot_directory in path:
64
+ python_path = "%s%s%s" % (boot_directory, os.path.pathsep,
65
+ os.environ['PYTHONPATH'])
66
+
67
+ os.environ['PYTHONPATH'] = python_path
68
+
69
+ program_exe_path = args[0]
70
+ if not os.path.dirname(program_exe_path):
71
+ program_search_path = os.environ.get('PATH', '').split(os.path.pathsep)
72
+ for path in program_search_path:
73
+ path = os.path.join(path, program_exe_path)
74
+ # On Windows, X_OK check is unreliable, so just check existence
75
+ if sys.platform == 'win32':
76
+ if os.path.exists(path):
77
+ program_exe_path = path
78
+ break
79
+ else:
80
+ if os.path.exists(path) and os.access(path, os.X_OK):
81
+ program_exe_path = path
82
+ break
83
+
84
+ port = None
85
+ try:
86
+ port = configPort()
87
+ except Exception as e:
88
+ print('WHATAP: AGENT ERROR: {}'.format(e))
89
+ print('WHATAP: continue to start user application')
90
+
91
+ if port:
92
+ apm_enabled = preview_whatap_conf("apm_enabled")
93
+ llm_enabled = preview_whatap_conf("llm_enabled")
94
+
95
+ if apm_enabled == 'true':
96
+ try:
97
+ go(opts={'whatap.port': str(port)})
98
+ standalone_enabled = preview_whatap_conf("standalone_enabled")
99
+ if standalone_enabled == 'true':
100
+ time.sleep(1)
101
+ except Exception as e:
102
+ print('WHATAP: AGENT ERROR: {}'.format(e))
103
+ print('WHATAP: continue to start user application')
104
+
105
+ if llm_enabled == 'true':
106
+ try:
107
+ llm_port = configLlmPort()
108
+ if llm_port:
109
+ go(opts={'whatap.port': str(port)}, llm=True)
110
+ else:
111
+ print('WHATAP: LLM port allocation failed')
112
+ except Exception as e:
113
+ print('WHATAP: LLM AGENT ERROR: {}'.format(e))
114
+
115
+ try:
116
+ if sys.platform == 'win32':
117
+ # Windows: use subprocess instead of execl
118
+ import subprocess
119
+ result = subprocess.call(args)
120
+ sys.exit(result)
121
+ else:
122
+ # Unix/Linux: use execl to replace current process
123
+ os.execl(program_exe_path, *args)
124
+ except Exception as e:
125
+ print('WHATAP: INVALID ARGMENTS.')
126
+ print(start_agent.__doc__)
127
+
128
+
129
+ OPTIONS = ['--host', '--license', '--app_name', '--app_process_name']
130
+
131
+
132
+ @whatap_command
133
+ def setting_config():
134
+ """
135
+ Usage:
136
+ whatap-setting-config [--host HOST_ADDR]
137
+ [--license LICENSE_KEY]
138
+ [--app_name APPLICATION_NAME]
139
+ [--app_process_name APPLICATION_PROCESS_NAME]
140
+ """
141
+ home = 'WHATAP_HOME'
142
+ if init_config(home):
143
+ print('WHATAP:')
144
+ args = ' '.join(sys.argv[1:])
145
+ is_success=False
146
+ for opt in OPTIONS:
147
+ key = opt.split('--')[1]
148
+ m = re.match(r"[\s\w\-\_\.\/]*" + key + " (?P<key>[\w\-\_\.\/]*)", args)
149
+ if m:
150
+ if key == 'host':
151
+ key = 'whatap.server.{}'.format(key)
152
+ update_config(home, key, m.group('key'))
153
+ print('\t{}={}'.format(key, m.group('key')))
154
+ is_success = True
155
+
156
+ update_config(home, 'apm_enabled', 'true')
157
+ update_config(home, 'llm_enabled', 'false')
158
+ print('\tapm_enabled=true')
159
+ print('\tllm_enabled=false')
160
+
161
+ if is_success:
162
+ print('SUCCESS!')
163
+ else:
164
+ print(setting_config.__doc__)
165
+
166
+
167
+ LLM_OPTIONS = ['--host', '--license', '--app_name', '--app_process_name']
168
+
169
+
170
+ @whatap_command
171
+ def llm_setting_config():
172
+ """
173
+ Usage:
174
+ whatap-llm-setting-config [--host HOST_ADDR]
175
+ [--license LICENSE_KEY]
176
+ [--app_name APPLICATION_NAME]
177
+ [--app_process_name APPLICATION_PROCESS_NAME]
178
+ """
179
+ home = 'WHATAP_HOME'
180
+ if init_config(home):
181
+ print('WHATAP:')
182
+ args = ' '.join(sys.argv[1:])
183
+ is_success=False
184
+ for opt in LLM_OPTIONS:
185
+ key = opt.split('--')[1]
186
+ m = re.match(r"[\s\w\-\_\.\/]*" + key + " (?P<key>[\w\-\_\.\/]*)", args)
187
+ if m:
188
+ if key == 'host':
189
+ key = 'llm.whatap.server.{}'.format(key)
190
+ elif key == 'license':
191
+ key = 'llm_accesskey'
192
+ update_config(home, key, m.group('key'))
193
+ print('\t{}={}'.format(key, m.group('key')))
194
+ is_success = True
195
+
196
+ update_config(home, 'apm_enabled', 'false')
197
+ update_config(home, 'llm_enabled', 'true')
198
+ update_config(home, 'counter_thread_enabled', 'true')
199
+ print('\tapm_enabled=false')
200
+ print('\tllm_enabled=true')
201
+ print('\tcounter_thread_enabled=true')
202
+
203
+ if is_success:
204
+ print('SUCCESS!')
205
+ else:
206
+ print(llm_setting_config.__doc__)
207
+
208
+
@@ -0,0 +1,12 @@
1
+ import ctypes
2
+
3
+ from whatap.trace.trace_context_manager import TraceContextManager
4
+
5
+ _get_dict = ctypes.pythonapi._PyObject_GetDictPtr
6
+ _get_dict.restype = ctypes.POINTER(ctypes.py_object)
7
+ _get_dict.argtypes = [ctypes.py_object]
8
+
9
+
10
+ def get_dict(obj):
11
+ return _get_dict(obj).contents.value
12
+
File without changes
File without changes
@@ -0,0 +1,122 @@
1
+ from whatap.trace import get_dict
2
+ from whatap.trace.trace_handler import trace_handler
3
+ from whatap.trace.trace_error import interceptor_step_error
4
+ from whatap.trace.mod.application.wsgi import \
5
+ start_interceptor, end_interceptor
6
+ from whatap.trace.trace_context import TraceContext
7
+ from whatap.trace.trace_context_manager import TraceContextManager
8
+ import whatap.net.async_sender as async_sender
9
+ from whatap.net.packet_type_enum import PacketTypeEnum
10
+ from whatap.util.date_util import DateUtil
11
+
12
+ def parseCallbackName(args):
13
+ if args:
14
+ receiver = args[0]
15
+ callbackspan = []
16
+
17
+ if len(args) > 2:
18
+ message = args[2]
19
+ if hasattr(message, 'delivery_info'):
20
+ if 'exchange' in message.delivery_info:
21
+ callbackspan.append(message.delivery_info['exchange'])
22
+ if 'routing_key' in message.delivery_info:
23
+ callbackspan.append(message.delivery_info['routing_key'])
24
+
25
+ if not callbackspan:
26
+ callback = receiver.callbacks[0]
27
+ if isinstance(callback, partial):
28
+ callback = callback.func
29
+
30
+ if hasattr(callback, '__qualname__'):
31
+ callbackspan.append(callback.__qualname__)
32
+ else:
33
+ if hasattr(callback, '__module__'):
34
+ callbackspan.append(callback.__module__)
35
+ if hasattr(callback, '__self__'):
36
+ callbackspan.append(callback.__self__.__class__.__name__)
37
+ if hasattr(callback, '__name__'):
38
+ callbackspan.append(callback.__name__)
39
+
40
+ return '.'.join(callbackspan)
41
+ return ''
42
+
43
+ def intercept_receive(fn, *args, **kwargs):
44
+ ctx = TraceContext()
45
+ ctx.service_name = parseCallbackName(args)
46
+ start_interceptor(ctx)
47
+
48
+ try:
49
+ callback = fn(*args, **kwargs)
50
+ ctx = TraceContextManager.getLocalContext()
51
+ return callback
52
+ except Exception as e:
53
+ interceptor_step_error(e)
54
+ finally:
55
+ if ctx:
56
+ end_interceptor(ctx=ctx)
57
+
58
+ def parseConnection(conn):
59
+ connstr = ''
60
+ if conn.host:
61
+ connstr += conn.host
62
+ if conn.virtual_host:
63
+ connstr += "/" + conn.virtual_host
64
+ return connstr
65
+
66
+ def intercept_publish(fn, *args, **kwargs):
67
+ ctx = TraceContextManager.getLocalContext()
68
+
69
+ start_time = DateUtil.nowSystem()
70
+ ctx.start_time = start_time
71
+
72
+ text = 'rabbitmq://'
73
+ text += parseConnection(args[0].channel.connection)
74
+ text += '?exchage='
75
+ text += args[10]
76
+ text += '&routing='
77
+ text += args[7]
78
+ ctx.active_dbc = text
79
+ ctx.lctx['dbc'] = text
80
+
81
+ ctx.active_dbc = 0
82
+ ctx.db_opening = True
83
+ ctx.elapsed = DateUtil.nowSystem() - start_time
84
+
85
+ datas = [' ', ' ', 'MQ SESSION INFO: ' + text]
86
+ async_sender.send_packet(PacketTypeEnum.TX_MSG, ctx, datas)
87
+
88
+
89
+ start_time = DateUtil.nowSystem()
90
+ ctx.start_time = start_time
91
+
92
+ try:
93
+ callback = fn( *args, **kwargs)
94
+ return callback
95
+ except Exception as e:
96
+ interceptor_step_error(e)
97
+ finally:
98
+ ctx.db_opening = False
99
+
100
+ def instrument_kombu(module):
101
+ def wrapper(fn):
102
+ @trace_handler(fn)
103
+ def trace(*args, **kwargs):
104
+ callback = intercept_publish(fn, *args, **kwargs)
105
+ return callback
106
+
107
+ return trace
108
+
109
+ if hasattr(module, 'Producer') and hasattr(module.Producer, '_publish'):
110
+ module.Producer._publish = wrapper(module.Producer._publish)
111
+
112
+ def wrapper(fn):
113
+ @trace_handler(fn, start=True)
114
+ def trace(*args, **kwargs):
115
+ callback = intercept_receive(fn, *args, **kwargs)
116
+ return callback
117
+
118
+ return trace
119
+
120
+ if hasattr(module, 'Consumer') and hasattr(module.Consumer, 'receive'):
121
+ module.Consumer.receive = wrapper(module.Consumer.receive)
122
+
@@ -0,0 +1,62 @@
1
+ from whatap.trace import get_dict
2
+ from whatap.trace.trace_handler import trace_handler
3
+ from whatap.trace.trace_error import interceptor_step_error
4
+ from whatap.trace.mod.application.wsgi import \
5
+ start_interceptor, end_interceptor
6
+ from whatap.trace.trace_context import TraceContext
7
+ from whatap.trace.trace_context_manager import TraceContextManager
8
+ import whatap.net.async_sender as async_sender
9
+ from whatap.net.packet_type_enum import PacketTypeEnum
10
+ from whatap.util.date_util import DateUtil
11
+
12
+
13
+ def parseConnection(conn):
14
+ connstr = ''
15
+ if conn.host:
16
+ connstr += conn.host
17
+ if conn.virtual_host:
18
+ connstr += "/" + conn.virtual_host
19
+ return connstr
20
+
21
+
22
+ def intercept_publish(fn, *args, **kwargs):
23
+ ctx = TraceContextManager.getLocalContext()
24
+
25
+ start_time = DateUtil.nowSystem()
26
+ ctx.start_time = start_time
27
+ text = 'rabbitmq://'
28
+ text += parseConnection(args[0].connection.params)
29
+ text += '?exchage='
30
+ text += kwargs['exchange']
31
+ text += '&routing='
32
+ text += kwargs['routing_key']
33
+ ctx.active_dbc = text
34
+ ctx.lctx['dbc'] = text
35
+
36
+ try:
37
+ result = fn(*args, **kwargs)
38
+
39
+ ctx.active_dbc = 0
40
+ ctx.db_opening = True
41
+ ctx.elapsed = DateUtil.nowSystem() - start_time
42
+ datas = [' ', ' ', 'MQ SESSION INFO: ' + text]
43
+ async_sender.send_packet(PacketTypeEnum.TX_MSG, ctx, datas)
44
+
45
+ return result
46
+ except Exception as e:
47
+ ctx.active_dbc = 0
48
+ ctx.db_opening = False
49
+ ctx.elapsed = DateUtil.nowSystem() - start_time
50
+ raise e
51
+
52
+
53
+ def instrument_pika(module):
54
+ def wrapper(fn):
55
+ @trace_handler(fn)
56
+ def trace(*args, **kwargs):
57
+ return intercept_publish(fn, *args, **kwargs)
58
+
59
+ return trace
60
+
61
+ if hasattr(module, 'Channel') and hasattr(module.Channel, 'basic_publish'):
62
+ module.Channel.basic_publish = wrapper(module.Channel.basic_publish)
File without changes
@@ -0,0 +1,34 @@
1
+ from whatap.trace.trace_handler import trace_handler
2
+ from whatap.trace.trace_error import interceptor_error
3
+ from whatap.trace.mod.application.wsgi import interceptor
4
+
5
+
6
+ def instrument(module):
7
+ def wrapper(fn):
8
+ @trace_handler(fn, True)
9
+ def trace(*args, **kwargs):
10
+ callback = interceptor(fn, *args, **kwargs)
11
+ return callback
12
+
13
+ return trace
14
+
15
+ module.Bottle.__call__ = wrapper(module.Bottle.__call__)
16
+
17
+ def wrapper(fn):
18
+ @trace_handler(fn)
19
+ def trace(*args, **kwargs):
20
+ callback = fn(*args, **kwargs)
21
+ if len(args) > 3:
22
+ e = args[3]
23
+ status_code = args[1]
24
+ else:
25
+ e = args[0]
26
+ status_code = e._status_code
27
+
28
+ errors = [e.__class__.__name__, str(e)]
29
+ interceptor_error(status_code, errors)
30
+ return callback
31
+
32
+ return trace
33
+
34
+ module.HTTPError.__init__ = wrapper(module.HTTPError.__init__)
@@ -0,0 +1,81 @@
1
+ from functools import wraps
2
+ from whatap.trace.trace_context import TraceContext
3
+ from whatap.trace.trace_context_manager import TraceContextManager
4
+ from whatap.trace.trace_error import interceptor_step_error
5
+ from whatap.trace.mod.application.wsgi import start_interceptor, end_interceptor
6
+ from whatap import logging
7
+ from whatap.conf.configure import Configure as conf
8
+ import time
9
+
10
+ def interceptor(fn, task_name, *args, **kwargs):
11
+ now = time.time()
12
+ if now - conf.last_loaded > conf.init_load_interval/1000:
13
+ conf.init(False)
14
+ ctx = TraceContext()
15
+ ctx.service_name = task_name
16
+ start_interceptor(ctx)
17
+ try:
18
+ callback = fn(*args, **kwargs)
19
+ ctx = TraceContextManager.getLocalContext()
20
+ return callback
21
+ except Exception as e:
22
+ interceptor_step_error(e)
23
+ raise e
24
+ finally:
25
+ if ctx:
26
+ end_interceptor(ctx=ctx)
27
+
28
+ def trace_handler(fn, start=False):
29
+ def handler(func):
30
+ @wraps(func)
31
+ def wrapper(*args, **kwargs):
32
+
33
+ ctx = TraceContextManager.getLocalContext()
34
+
35
+ if not start and not ctx:
36
+ return fn(*args, **kwargs)
37
+
38
+ try:
39
+ callback = func(*args, **kwargs)
40
+ except Exception as e:
41
+ ctx = TraceContextManager.getLocalContext()
42
+ if ctx and ctx.error_step == e:
43
+ ctx.error_step = None
44
+ raise e
45
+ raise
46
+ else:
47
+ ctx = TraceContextManager.getLocalContext()
48
+ if ctx and ctx.error_step:
49
+ e = ctx.error_step
50
+ ctx.error_step = None
51
+ raise e
52
+ return callback
53
+
54
+ return wrapper
55
+
56
+ return handler
57
+
58
+ celery_injection_processed = False
59
+ def instrument_celery_execute_trace(module):
60
+ global celery_injection_processed
61
+ if celery_injection_processed:
62
+ return
63
+ def wrapper(fn, task_name):
64
+ @trace_handler(fn, start=True)
65
+ def trace(*args, **kwargs):
66
+ callback = interceptor(fn, task_name, *args, **kwargs)
67
+ return callback
68
+
69
+ return trace
70
+ if hasattr(module, 'build_tracer'):
71
+ _build_tracer = module.build_tracer
72
+ def build_tracer(name, task,*args, **kwargs):
73
+ task = task or module.tasks[name]
74
+ name = ''
75
+ if hasattr(task,'name'):
76
+ name = task.name
77
+ task.run = wrapper(task.run, name)
78
+ return _build_tracer(name, task,*args, **kwargs)
79
+
80
+ module.build_tracer = build_tracer
81
+ celery_injection_processed = True
@@ -0,0 +1,30 @@
1
+ from whatap.trace.trace_handler import trace_handler
2
+ from whatap.trace.trace_error import interceptor_error
3
+ from whatap.trace.mod.application.wsgi import interceptor
4
+
5
+
6
+ def instrument(module):
7
+ def wrapper(fn):
8
+ @trace_handler(fn, True)
9
+ def trace(*args, **kwargs):
10
+ callback = interceptor(fn, *args, **kwargs)
11
+ return callback
12
+
13
+ return trace
14
+
15
+ module.Application.__call__ = wrapper(module.Application.__call__)
16
+
17
+ def wrapper(fn):
18
+ @trace_handler(fn)
19
+ def trace(*args, **kwargs):
20
+ callback = fn(*args, **kwargs)
21
+
22
+ e = args[0]
23
+ status_code = e.code
24
+ errors = [e.reason, e._message]
25
+ interceptor_error(status_code, errors)
26
+ return callback
27
+
28
+ return trace
29
+
30
+ module.HTTPError.set_response = wrapper(module.HTTPError.set_response)