def __init__(self):
        self.grantee_key = None
        raw_key = getenv(CONF_KEY_GRANTEE, None)
        if (raw_key and len(raw_key.strip()) > 0):
            self.grantee_key = raw_key.strip()

        if (self.grantee_key):
            self.sender = AsynchronousSender()
            self.r_queue = AsynchronousQueue(self.sender)
            self.r_context = AI4ETelemetryContext()
            self.r_channel = TelemetryChannel(self.r_context, self.r_queue)

            self.appinsights_grantee_client = TelemetryClient(
                getenv(CONF_KEY_GRANTEE), self.r_channel)
            self.appinsights_ai4e_client = None

            if (getenv(CONF_KEY_AI4E)):
                self.appinsights_ai4e_client = TelemetryClient(
                    getenv(CONF_KEY_AI4E), self.r_channel)
Exemplo n.º 2
0
def upload(data_to_save):
    data_to_save = json.loads(data_to_save)

    for instrumentation_key in data_to_save:
        client = TelemetryClient(instrumentation_key=instrumentation_key,
                                 telemetry_channel=TelemetryChannel(queue=SynchronousQueue(LimitedRetrySender())))
        enable(instrumentation_key)
        for record in data_to_save[instrumentation_key]:
            name = record['name']
            raw_properties = record['properties']
            properties = {}
            measurements = {}
            for k, v in raw_properties.items():
                if isinstance(v, str):
                    properties[k] = v
                else:
                    measurements[k] = v
            client.track_event(name, properties, measurements)
        client.flush()
Exemplo n.º 3
0
def __enable_for_urllib3(http_connection_pool_class,
                         https_connection_pool_class, instrumentation_key,
                         telemetry_channel, always_flush):
    if not instrumentation_key:
        raise Exception('Instrumentation key was required but not provided')

    if telemetry_channel is None:
        sender = SynchronousSender()
        queue = SynchronousQueue(sender)
        telemetry_channel = TelemetryChannel(None, queue)

    client = TelemetryClient(instrumentation_key, telemetry_channel)

    orig_http_urlopen_method = http_connection_pool_class.urlopen
    orig_https_urlopen_method = https_connection_pool_class.urlopen

    def custom_urlopen_wrapper(urlopen_func):
        def custom_urlopen(*args, **kwargs):
            start_time = current_milli_time()
            response = urlopen_func(*args, **kwargs)
            try:  # make sure to always return the response
                duration = current_milli_time() - start_time
                try:
                    method = args[1]
                except IndexError:
                    method = kwargs['method']

                try:
                    url = args[2]
                except IndexError:
                    url = kwargs['url']

                _track_dependency(client, always_flush, args[0].host, method,
                                  url, duration, response.status)
            finally:
                return response

        return custom_urlopen

    http_connection_pool_class.urlopen = custom_urlopen_wrapper(
        orig_http_urlopen_method)
    https_connection_pool_class.urlopen = custom_urlopen_wrapper(
        orig_https_urlopen_method)
def upload(data_to_save):
    if in_diagnostic_mode():
        sys.stdout.write('Telemetry upload begins\n')
        sys.stdout.write('Got data {}\n'.format(
            json.dumps(json.loads(data_to_save), indent=2)))

    try:
        data_to_save = json.loads(data_to_save.replace("'", '"'))
    except Exception as err:  # pylint: disable=broad-except
        if in_diagnostic_mode():
            sys.stdout.write('ERROR: {}/n'.format(str(err)))
            sys.stdout.write('Raw [{}]/n'.format(data_to_save))

    for instrumentation_key in data_to_save:
        client = TelemetryClient(
            instrumentation_key=instrumentation_key,
            telemetry_channel=TelemetryChannel(
                queue=SynchronousQueue(LimitedRetrySender())))
        enable(instrumentation_key)

        for record in data_to_save[instrumentation_key]:
            name = record['name']
            raw_properties = record['properties']
            properties = {}
            measurements = {}
            for k, v in raw_properties.items():
                if isinstance(v, six.string_types):
                    properties[k] = v
                else:
                    measurements[k] = v
            client.track_event(record['name'], properties, measurements)

            if in_diagnostic_mode():
                sys.stdout.write(
                    '\nTrack Event: {}\nProperties: {}\nMeasurements: {}'.
                    format(name, json.dumps(properties, indent=2),
                           json.dumps(measurements, indent=2)))

        client.flush()

    if in_diagnostic_mode():
        sys.stdout.write('\nTelemetry upload completes\n')
Exemplo n.º 5
0
    def setup(self, app):
        """
        Initializes the plugin for the provided Bottle application.

        Args:
            app (bottle.Bottle). the Bottle application for which to initialize the extension.
        """
        self._key = app.config.get(CONF_KEY) or getenv(CONF_KEY)

        if not self._key:
            return

        self._endpoint_uri = app.config.get(CONF_ENDPOINT_URI)
        sender = AsynchronousSender(self._endpoint_uri)

        queue = AsynchronousQueue(sender)
        self._channel = TelemetryChannel(None, queue)
        self._tc = TelemetryClient(self._key, self._channel)

        self.context.cloud.role_instance = platform.node()
Exemplo n.º 6
0
    def init_app(self, app):
        """
        Initializes the extension for the provided Flask application.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        self._key = app.config.get(CONF_KEY) or getenv(CONF_KEY)

        if not self._key:
            return

        self._endpoint_uri = app.config.get(CONF_ENDPOINT_URI)
        sender = AsynchronousSender(self._endpoint_uri)

        queue = AsynchronousQueue(sender)
        self._channel = TelemetryChannel(None, queue)

        self._init_request_logging(app)
        self._init_trace_logging(app)
        self._init_exception_logging(app)
Exemplo n.º 7
0
def __enable_for_urllib(base_http_handler_class,
                        base_https_handler_class,
                        instrumentation_key,
                        telemetry_channel=None,
                        always_flush=False):
    pass
    if not instrumentation_key:
        raise Exception('Instrumentation key was required but not provided')

    if telemetry_channel is None:
        sender = SynchronousSender()
        queue = SynchronousQueue(sender)
        telemetry_channel = TelemetryChannel(None, queue)

    client = TelemetryClient(instrumentation_key, telemetry_channel)

    class AppInsightsHTTPHandler(base_http_handler_class, object):
        def http_open(self, req):
            start_time = current_milli_time()
            response = super(AppInsightsHTTPHandler, self).http_open(req)

            try:
                _track_for_urllib(client, always_flush, start_time, req,
                                  response)
            finally:
                return response

    class AppInsightsHTTPSHandler(base_https_handler_class, object):
        def https_open(self, req):
            start_time = current_milli_time()
            response = super(AppInsightsHTTPSHandler, self).https_open(req)

            try:
                _track_for_urllib(client, always_flush, start_time, req,
                                  response)
            finally:
                return response

    return AppInsightsHTTPHandler, AppInsightsHTTPSHandler
Exemplo n.º 8
0
    def init_app(self, app, context):
        """
        Initializes the extension for the provided Flask application.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        print("Starting application insights module.")
        self._appinsights_key = app.config.get(
            APPINSIGHTS_INSTRUMENTATIONKEY) or getenv(
                APPINSIGHTS_INSTRUMENTATIONKEY)

        if self._appinsights_key and len(self._appinsights_key.strip()) > 0:
            self._appinsights_key = self._appinsights_key.strip()
        else:
            self._appinsights_key = None

        # Set the application insights key for production use.
        if self._appinsights_key:
            print("Application insights key set.")

        self._endpoint_uri = app.config.get(CONF_ENDPOINT_URI)

        if self._endpoint_uri:
            sender = AsynchronousSender(self._endpoint_uri)
        else:
            sender = AsynchronousSender()

        queue = AsynchronousQueue(sender)

        if not context:
            context = AI4ETelemetryContext()

        self._channel = TelemetryChannel(context, queue)

        self._init_request_logging(app)
        self._init_trace_logging(app)
        self._init_exception_logging(app)
Exemplo n.º 9
0
def _create_telemetry_channel() -> TelemetryChannel:
    sender = AsynchronousSender(
        APPINSIGHTS_HOST) if APPINSIGHTS_HOST else NullSender()
    queue = AsynchronousQueue(sender)
    return TelemetryChannel(queue=queue)