|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +'''This example demonstrates instrumenting a (mocked) application that executes |
| 3 | +a remote call that sometimes fails and does some database operations.''' |
| 4 | + |
| 5 | +from __future__ import print_function # Python 2 compatibility. |
| 6 | + |
| 7 | +import threading |
| 8 | + |
| 9 | +import oneagent # SDK initialization functions |
| 10 | +import oneagent.sdk as onesdk # All other SDK functions. |
| 11 | + |
| 12 | +try: # Python 2 compatibility. |
| 13 | + input = raw_input #pylint:disable=redefined-builtin |
| 14 | +except NameError: |
| 15 | + pass |
| 16 | + |
| 17 | +getsdk = onesdk.SDK.get # Just to make the code shorter. |
| 18 | + |
| 19 | +def traced_db_operation(dbinfo, sql): |
| 20 | + print('+db', dbinfo, sql) |
| 21 | + |
| 22 | + # Entering the with block automatically start the tracer. |
| 23 | + with getsdk().trace_sql_database_request(dbinfo, sql) as tracer: |
| 24 | + |
| 25 | + # In real-world code, you would do the actual database operation here, |
| 26 | + # i.e. call the database's API. |
| 27 | + |
| 28 | + # Set an optional "exit"-field on the tracer. Whenever there is a |
| 29 | + # setter available on a tracer (as opposed to an optional parameter to a |
| 30 | + # trace_* function), it may be called anytime between creating and |
| 31 | + # ending the tracer (i.e. also after starting it). |
| 32 | + tracer.set_round_trip_count(3) |
| 33 | + |
| 34 | + print('-db', dbinfo, sql) |
| 35 | + |
| 36 | +def outgoing_remote_call(success): |
| 37 | + print('+remote') |
| 38 | + |
| 39 | + # We use positional arguments to specify required values and named arguments |
| 40 | + # to specify optional values. |
| 41 | + call = getsdk().trace_outgoing_remote_call( |
| 42 | + 'dummyPyMethod', 'DummyPyService', 'dupypr://localhost/dummyEndpoint', |
| 43 | + onesdk.Channel(onesdk.ChannelType.IN_PROCESS, 'localhost'), |
| 44 | + protocol_name='DUMMY_PY_PROTOCOL') |
| 45 | + try: |
| 46 | + with call: |
| 47 | + |
| 48 | + # Note that this property can only be accessed after starting the |
| 49 | + # tracer. See the documentation on tagging for more information. |
| 50 | + strtag = call.outgoing_dynatrace_string_tag |
| 51 | + |
| 52 | + if not success: |
| 53 | + # This demonstrates how an exception leaving a tracer's |
| 54 | + # with-block will mark the tracer as failed. |
| 55 | + raise RuntimeError('remote error message') |
| 56 | + do_remote_call(strtag) |
| 57 | + except RuntimeError: # Swallow the exception raised above. |
| 58 | + pass |
| 59 | + print('-remote') |
| 60 | + |
| 61 | +failed = [False] |
| 62 | + |
| 63 | +def do_remote_call_thread_func(strtag): |
| 64 | + try: |
| 65 | + print('+thread') |
| 66 | + # We use positional arguments to specify required values and named |
| 67 | + # arguments to specify optional values. |
| 68 | + incall = getsdk().trace_incoming_remote_call( |
| 69 | + 'dummyPyMethod', 'DummyPyService', |
| 70 | + 'dupypr://localhost/dummyEndpoint', |
| 71 | + protocol_name='DUMMY_PY_PROTOCOL', str_tag=strtag) |
| 72 | + with incall: |
| 73 | + dbinfo = getsdk().create_database_info( |
| 74 | + 'Northwind', onesdk.DatabaseVendor.SQLSERVER, |
| 75 | + onesdk.Channel(onesdk.ChannelType.TCP_IP, '10.0.0.42:6666')) |
| 76 | + |
| 77 | + # This with-block will automatically free the database info handle |
| 78 | + # at the end. Note that the handle is used for multiple tracers. In |
| 79 | + # general, it is recommended to reuse database (and web application) |
| 80 | + # info handles as often as possible (for efficiency reasons). |
| 81 | + with dbinfo: |
| 82 | + traced_db_operation( |
| 83 | + dbinfo, "BEGIN TRAN;") |
| 84 | + traced_db_operation( |
| 85 | + dbinfo, |
| 86 | + "SELECT TOP 1 qux FROM baz ORDER BY quux;") |
| 87 | + traced_db_operation( |
| 88 | + dbinfo, |
| 89 | + "SELECT foo, bar FROM baz WHERE qux = 23") |
| 90 | + traced_db_operation( |
| 91 | + dbinfo, |
| 92 | + "UPDATE baz SET foo = foo + 1 WHERE qux = 23;") |
| 93 | + traced_db_operation(dbinfo, "COMMIT;") |
| 94 | + print('-thread') |
| 95 | + except Exception: |
| 96 | + failed[0] = True |
| 97 | + raise |
| 98 | + |
| 99 | + |
| 100 | +def do_remote_call(strtag): |
| 101 | + # This function simulates doing a remote call by calling a function |
| 102 | + # do_remote_call_thread_func in another thread, passing a string tag. See |
| 103 | + # the documentation on tagging for more information. |
| 104 | + |
| 105 | + workerthread = threading.Thread( |
| 106 | + target=do_remote_call_thread_func, |
| 107 | + args=(strtag,)) |
| 108 | + workerthread.start() |
| 109 | + |
| 110 | + # Note that we need to join the thread, as all tagging assumes synchronous |
| 111 | + # calls. |
| 112 | + workerthread.join() |
| 113 | + |
| 114 | + assert not failed[0] |
| 115 | + |
| 116 | +def mock_incoming_web_request(): |
| 117 | + sdk = getsdk() |
| 118 | + wappinfo = sdk.create_web_application_info( |
| 119 | + virtual_host='example.com', # Logical name of the host server. |
| 120 | + application_id='MyWebApplication', # Unique web application ID. |
| 121 | + context_root='/my-web-app/') # App's prefix of the path part of the URL. |
| 122 | + |
| 123 | + with wappinfo: |
| 124 | + # This with-block will automatically free web application info handle |
| 125 | + # at the end. Note that the handle can be used for multiple tracers. In |
| 126 | + # general, it is recommended to reuse web application info handles as |
| 127 | + # often as possible (for efficiency reasons). For example, if you use |
| 128 | + # WSGI, the web application info could be stored as an attribute of the |
| 129 | + # application object. |
| 130 | + # |
| 131 | + # Note that different ways to specify headers, response headers and |
| 132 | + # parameter (form fields) not shown here also exist. Consult the |
| 133 | + # documentation for trace_incoming_web_request and |
| 134 | + # IncomingWebRequestTracer. |
| 135 | + wreq = sdk.trace_incoming_web_request( |
| 136 | + wappinfo, |
| 137 | + 'http://example.com/my-web-app/foo?bar=baz', |
| 138 | + 'GET', |
| 139 | + headers={'Host': 'example.com', 'X-foo': 'bar'}, |
| 140 | + remote_address='127.0.0.1:12345') |
| 141 | + with wreq: |
| 142 | + wreq.add_parameter('my_form_field', '1234') |
| 143 | + # Process web request |
| 144 | + wreq.add_response_headers({'Content-Length': '1234'}) |
| 145 | + wreq.set_status_code(200) # OK |
| 146 | + |
| 147 | + |
| 148 | +def main(): |
| 149 | + print('+main') |
| 150 | + |
| 151 | + # This gathers arguments prefixed with '--dt_' from sys.argv into the |
| 152 | + # returned list. See try_init below. |
| 153 | + sdk_options = oneagent.sdkopts_from_commandline(remove=True) |
| 154 | + |
| 155 | + # If you do not call try_init() manually, the first call to |
| 156 | + # oneagent.sdk.SDK.get() will attempt to initialize the SDK with default |
| 157 | + # options, swallowing any errors, which is why manually calling try_init() |
| 158 | + # is recommended. |
| 159 | + # Passing in the sdk_options is entirely optional and usually not required |
| 160 | + # as all settings will be automatically provided by the Dynatrace OneAgent |
| 161 | + # that is installed on the host. |
| 162 | + init_result = oneagent.try_init(sdk_options) |
| 163 | + try: |
| 164 | + if init_result.error is not None: |
| 165 | + print('Error during SDK initialization:', init_result.error) |
| 166 | + |
| 167 | + # While not by much, it is a bit faster to cache the result of |
| 168 | + # oneagent.sdk.SDK.get() instead of calling the function multiple times. |
| 169 | + sdk = getsdk() |
| 170 | + |
| 171 | + # The agent state is one of the integers in oneagent.sdk.AgentState. |
| 172 | + print('Agent state:', sdk.agent_state) |
| 173 | + |
| 174 | + # The agent version is the version of the installed OneAgent, not the |
| 175 | + # version of the SDK. |
| 176 | + print('Agent version:', sdk.agent_version_string) |
| 177 | + |
| 178 | + mock_incoming_web_request() |
| 179 | + |
| 180 | + # We use trace_incoming_remote_call here, because it is one of the few |
| 181 | + # calls that create a new path if none is running yet. |
| 182 | + with sdk.trace_incoming_remote_call('main', 'main', 'main'): |
| 183 | + # Simulate some remote calls |
| 184 | + outgoing_remote_call(success=True) |
| 185 | + outgoing_remote_call(success=True) |
| 186 | + outgoing_remote_call(success=False) |
| 187 | + print('-main') |
| 188 | + input('Now wait until the path appears in the UI...') |
| 189 | + finally: |
| 190 | + shutdown_error = oneagent.shutdown() |
| 191 | + if shutdown_error: |
| 192 | + print('Error shutting down SDK:', shutdown_error) |
| 193 | + |
| 194 | +if __name__ == '__main__': |
| 195 | + main() |
0 commit comments