Exemplo n.º 1
0
def init(forkable=False):
    global sdk
    oneagent.initialize(forkable=forkable)
    state = oneagent.get_sdk().agent_state
    if state != oneagent.common.AgentState.ACTIVE:
        logger.warning(
            "Could not initialize the OneAgent SDK, AgentState: {}".format(
                state))

    atexit.register(shutdown)
    sdk = oneagent.get_sdk()
Exemplo n.º 2
0
    def __init__(self):
        oneagent.initialize()

        if self.sdk is None:
            self.sdk = oneagent.get_sdk()

        if self. db_info is None:
            self.db_info = self.sdk.create_database_info('Polls',
                                                         oneagent.sdk.DatabaseVendor.SQLITE,
                                                         oneagent.sdk.Channel(oneagent.sdk.ChannelType.TCP_IP,
                                                         '127.0.0.1:6666'))
Exemplo n.º 3
0
def get_sdk():
    oneagent.initialize()
    sdk = oneagent.get_sdk()

    if sdk.agent_state == 0:
        print("OneAgent initialized...")
        all_set = True
    else:
        print("OneAgent initialization failed...")
        print("Check that OneAgent is running...")
        all_set = False
    return all_set, sdk
Exemplo n.º 4
0
def init(forkable=False):
    global sdk
    try:
        oneagent.initialize(forkable=forkable)
    except TypeError:
        # older versions of the oneagent SDK don't support forkable
        oneagent.initialize()
    state = oneagent.get_sdk().agent_state
    logger.debug("Initialized snidynatrace with AgentState: {}".format(state))
    if state != oneagent.common.AgentState.ACTIVE:
        logger.warning(
            "Could not initialize the OneAgent SDK, AgentState: {}".format(
                state))

    atexit.register(shutdown)
    sdk = oneagent.get_sdk()
Exemplo n.º 5
0
def main():
    call_msg = []

    init_result = oneagent.initialize()
    if not init_result:
        print(init_result, file=sys.stderr)
        sys.exit(1)

    def diag_cb(msg):
        sys.stderr.flush()
        call_msg.append(msg)

    sdk = oneagent.get_sdk()
    try:
        sdk.set_diagnostic_callback(diag_cb)
        sdk.create_database_info(None, None, onesdk.Channel(0))
        gc.collect()
        gc.collect()
        gc.collect()
        print(call_msg)
        n_msgs = len(call_msg)

        # Database name must not be null (from CSDK), leaked db info handle
        assert n_msgs == 2

        assert all(isinstance(m, six.text_type) for m in call_msg)
        sdk.set_diagnostic_callback(None)
        sdk.create_database_info(None, None, onesdk.Channel(0))
        print(call_msg[n_msgs:])
        assert len(call_msg) == n_msgs
    finally:
        oneagent.shutdown()
Exemplo n.º 6
0
    def __init__(self, get_response):
        self.get_response = get_response
        oneagent.logger = logger

        if not oneagent.initialize():
            logger.error('Error initialiing OneAgent SDK')

        else:
            self.sdk = oneagent.get_sdk()

            self.wappinfo = self.sdk.create_web_application_info(
                virtual_host='example.com',
                application_id='DjangoApp',
                context_root='/')
Exemplo n.º 7
0
def main():
    # This gathers arguments prefixed with '--dt_' from sys.argv into the
    # returned list. See also the basic-sdk-sample.
    sdk_options = oneagent.sdkopts_from_commandline(remove=True)

    # Before using the SDK you have to initialize the OneAgent. In this scenario, we
    # initialize the SDK and prepare it for forking.
    #
    # Passing in the sdk_options is entirely optional and usually not required
    # as all settings will be automatically provided by the Dynatrace OneAgent
    # that is installed on the host.
    #
    # To activate the forking support add the optional 'forkable' parameter and set it to True.
    #
    # If you run this example on Windows then you'll get an "Invalid Argument" error back
    # because there's no forking support for Windows available.
    init_result = oneagent.initialize(sdk_options, forkable=True)
    try:
        if init_result.error is not None:
            print('Error during SDK initialization:', init_result.error)

        # While not by much, it is a bit faster to cache the result of
        # oneagent.get_sdk() instead of calling the function multiple times.
        sdk = getsdk()

        # The agent state is one of the integers in oneagent.sdk.AgentState.
        # Since we're using the 'forkable' mode the state will be TEMPORARILY_INACTIVE (1) on Linux.
        print('Agent state (parent process):', sdk.agent_state)

        # In the parent, the state will be PARENT_INITIALIZED (1).
        print('Agent fork state (parent process):', sdk.agent_fork_state)

        # The instance attribute 'agent_found' indicates whether an agent could be found or not.
        print('Agent found:', sdk.agent_found)

        # If an agent was found but it is incompatible with this version of the SDK for Python
        # then 'agent_is_compatible' would be set to false.
        print('Agent is compatible:', sdk.agent_is_compatible)

        # The agent version is a string holding both the OneAgent version and the
        # OneAgent SDK for C/C++ version separated by a '/'.
        print('Agent version:', sdk.agent_version_string)

        if init_result.error is None:
            fork_children()
            input('Now wait until the path appears in the UI ...')
    finally:
        shutdown_error = oneagent.shutdown()
        if shutdown_error:
            print('Error shutting down SDK:', shutdown_error)
Exemplo n.º 8
0
def main():
    signal.signal(signal.SIGTERM, shutdown_handler)
    signal.signal(signal.SIGINT, shutdown_handler)

    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logger.addFilter(LogLevelCountFilter())

    init_result = oneagent.initialize()
    if init_result.status is not InitResult.STATUS_INITIALIZED:
        logging.error(f'Error initializing OneAgent SDK. '
                      f'status = {init_result.status}, '
                      f'error = {init_result.error}')

    app = tornado.web.Application([
        (r'/test', TestHandler),
        (r'/metrics', MetricsHandler),
    ])
    app.listen(8080)
    tornado.ioloop.IOLoop.current().start()
def test_load_old_agent():
    saved_path = os.environ.get('DT_AGENTLIBRARY', '')
    try:
        assert os.environ['DT_OLDAGENTLIBRARY'] is not None
        assert os.environ['DT_OLDAGENTLIBRARY'] != ''
        os.environ['DT_AGENTLIBRARY'] = os.environ.get('DT_OLDAGENTLIBRARY', '')

        sdk_options = oneagent.sdkopts_from_commandline(remove=True)
        init_result = oneagent.initialize(sdk_options)
        assert init_result.error is not None
        assert init_result.status == InitResult.STATUS_INIT_ERROR

        sdk = oneagent.get_sdk()

        assert sdk.agent_state == AgentState.NOT_INITIALIZED
        assert sdk.agent_found
        assert not sdk.agent_is_compatible

        assert sdk.agent_version_string == '1.141.246.20180604-140607/' + shipped_c_stub_version
    finally:
        oneagent.shutdown()
        os.environ['DT_AGENTLIBRARY'] = saved_path
def main():
    import logging
    logger = logging.getLogger('py_sdk')
    logger.addHandler(logging.StreamHandler())
    logger.setLevel(logging.DEBUG)

    flags = sys.argv[1].split() if len(sys.argv) > 1 else ()
    if 'noc' in flags:
        sys.modules['oneagent._impl.native.sdkctypesiface'] = False

    if 'tryinit' in flags:
        init_result = oneagent.initialize(['loglevelsdk=finest'])
        if 'noc' in flags:
            assert not init_result
            assert init_result.status == init_result.STATUS_STUB_LOAD_ERROR
            assert isinstance(init_result.error, ImportError)
        else:
            assert init_result
            assert init_result.status == init_result.STATUS_INITIALIZED

    from test import onesdksamplepy
    onesdksamplepy.main()
    print('DONE.')
Exemplo n.º 11
0
def sdk_init():
    ''' Initialize OneAgent Python SDK '''
    sdk_options = oneagent.sdkopts_from_commandline(remove=True)
    init_result = oneagent.initialize(sdk_options)
    if init_result:
        print('SDK should work (but agent might be inactive).',
              file=sys.stderr)
    else:
        print(
            'SDK will definitely not work (i.e. functions will be no-ops); init_result =',
            init_result,
            file=sys.stderr)
        return False
    try:
        getsdk().set_diagnostic_callback(_diag_callback)
    finally:
        print('Agent state:', getsdk().agent_state, file=sys.stderr)
        print('Agent found:', getsdk().agent_found, file=sys.stderr)
        print('Agent is compatible:',
              getsdk().agent_is_compatible,
              file=sys.stderr)
        print('Agent version:', getsdk().agent_version_string, file=sys.stderr)

    return True
Exemplo n.º 12
0
            'PRODUCT_CATALOG_SERVICE_ADDR environment variable not set')
    logger.info("product catalog address: " + catalog_addr)
    channel = grpc.insecure_channel(catalog_addr)
    product_catalog_stub = demo_pb2_grpc.ProductCatalogServiceStub(channel)

    # create gRPC server
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),
                         interceptors=(tracer_interceptor, ))

    # add class to gRPC server
    service = RecommendationService()
    demo_pb2_grpc.add_RecommendationServiceServicer_to_server(service, server)
    health_pb2_grpc.add_HealthServicer_to_server(service, server)

    #init oneagent
    if not oneagent.initialize(['loglevelsdk=finest', 'loglevel=finest']):
        print('Error initializing OneAgent SDK.')

    # start server
    logger.info("listening on port: " + port)
    server.add_insecure_port('[::]:' + port)
    server.start()

    # keep alive
    try:
        while True:
            time.sleep(10000)
    except KeyboardInterrupt:
        server.stop(0)
        oneagent.shutdown()
def main():
    print('+main')

    # This gathers arguments prefixed with '--dt_' from sys.argv into the
    # returned list. See initialize below.
    sdk_options = oneagent.sdkopts_from_commandline(remove=True)

    # Before using the SDK you have to initialize the OneAgent. You can call oneagent.initialize()
    # as often as you want, but you also have to call oneagent.shutdown() for every call to
    # initialize() as well.
    #
    # Passing in the sdk_options is entirely optional and usually not required
    # as all settings will be automatically provided by the Dynatrace OneAgent
    # that is installed on the host.
    init_result = oneagent.initialize(sdk_options)
    try:
        if init_result.error is not None:
            print('Error during SDK initialization:', init_result.error)

        # While not by much, it is a bit faster to cache the result of
        # oneagent.get_sdk() instead of calling the function multiple times.
        sdk = getsdk()

        # Set the diagnostic callback. Strongly recommended.
        sdk.set_diagnostic_callback(_diag_callback)

        # Set the verbose callback.
        # Not recommended in production as lots of messages can be emitted.
        if IN_DEV_ENVIRONMENT:
            sdk.set_verbose_callback(_diag_callback)

        # The agent state is one of the integers in oneagent.sdk.AgentState.
        print('Agent state:', sdk.agent_state)

        # The instance attribute 'agent_found' indicates whether an agent could be found or not.
        print('Agent found:', sdk.agent_found)

        # If an agent was found but it is incompatible with this version of the SDK for Python
        # then 'agent_is_compatible' would be set to false.
        print('Agent is compatible:', sdk.agent_is_compatible)

        # The agent version is a string holding both the OneAgent version and the
        # OneAgent SDK for C/C++ version separated by a '/'.
        print('Agent version:', sdk.agent_version_string)

        mock_incoming_web_request()

        mock_outgoing_web_request()

        mock_outgoing_message()

        mock_custom_service()

        # We use trace_incoming_remote_call here, because it is one of the few
        # calls that create a new path if none is running yet.
        with sdk.trace_incoming_remote_call('main', 'main', 'main'):
            # We want to start an asynchronous execution at this time, so we create an
            # in-process link which we will use afterwards (or in a different thread).
            link = sdk.create_in_process_link()

            # Simulate some remote calls
            outgoing_remote_call(success=True)
            outgoing_remote_call(success=True)
            outgoing_remote_call(success=False)

        # Now the asynchronous execution starts. So we create an in-process tracer. We're using
        # the in-process link which we've created above. This link specifies where the traced
        # actions below will show up in the path.
        with sdk.trace_in_process_link(link):
            outgoing_remote_call(success=True)

        print('-main')
        input('Now wait until the path appears in the UI...')
    finally:
        shutdown_error = oneagent.shutdown()
        if shutdown_error:
            print('Error shutting down SDK:', shutdown_error)
Exemplo n.º 14
0
from flask import *
import autodynatrace
import oneagent
import json

from oneagent.common import DYNATRACE_HTTP_HEADER_NAME
app = Flask("Dynatrace Support Lab Landing Page")

init_result = oneagent.initialize()
print('OneAgent SDK initialization result' + repr(init_result))
if init_result:
    print('SDK should work (but agent might be inactive).')
else:
    print('SDK will definitely not work (i.e. functions will be no-ops):',
          init_result)

sdk = oneagent.get_sdk()


@autodynatrace.trace
@app.route("/", methods=['GET'])
def index():
    with open('./configData.json') as json_configData:
        dict_configData = json.load(json_configData)
    return render_template("index.html", dict_configData=dict_configData)


@app.route("/json", methods=['GET'])
def json_text():
    with open('./configData.json') as json_configData:
        return str(json_configData.read())
from timeit import default_timer as gtm

import oneagent

def bench():
    with oneagent.get_sdk().trace_incoming_remote_call('a', 'b', 'c'):
        tdf = 0
        t_tot = 0
        t_inner = None
        do_req = ur.AbstractHTTPHandler.do_request_
        def wrap_req(self, req):
            nonlocal tdf
            req.host # pylint:disable=pointless-statement
            tdf += gtm() - t_inner
            return do_req(self, req)
        ur.AbstractHTTPHandler.do_request_ = wrap_req
        ur.HTTPHandler.http_request = wrap_req
        for _ in range(1):
            t_inner = gtm()
            ur.urlopen('http://localhost:8000/polls').close()
            t_tot += gtm() - t_inner
        return t_tot, tdf

if __name__ == '__main__':
    oneagent.initialize()

    t_total, t_diff = bench()

    oneagent.shutdown()
    print(t_total, t_diff, t_diff / t_total)