Exemplo n.º 1
0
    def add_log_event(self, level, message):
        event = TelemetryEvent(TELEMETRY_LOG_EVENT_ID,
                               TELEMETRY_LOG_PROVIDER_ID)
        event.parameters.append(
            TelemetryEventParam(GuestAgentGenericLogsSchema.EventName,
                                WALAEventOperation.Log))
        event.parameters.append(
            TelemetryEventParam(GuestAgentGenericLogsSchema.CapabilityUsed,
                                logger.LogLevel.STRINGS[level]))
        event.parameters.append(
            TelemetryEventParam(
                GuestAgentGenericLogsSchema.Context1,
                str_to_encoded_ustr(self._clean_up_message(message))))
        event.parameters.append(
            TelemetryEventParam(
                GuestAgentGenericLogsSchema.Context2,
                datetime.utcnow().strftime(logger.Logger.LogTimeFormatInUTC)))
        event.parameters.append(
            TelemetryEventParam(GuestAgentGenericLogsSchema.Context3, ''))
        self.add_common_event_parameters(event, datetime.utcnow())

        data = get_properties(event)
        try:
            self.save_event(json.dumps(data))
        except EventError:
            pass
    def add_metric(self, category, counter, instance, value, log_event=False):
        """
        Create and save an event which contains a telemetry event.

        :param str category: The category of metric (e.g. "cpu", "memory")
        :param str counter: The specific metric within the category (e.g. "%idle")
        :param str instance: For instanced metrics, the instance identifier (filesystem name, cpu core#, etc.)
        :param value: Value of the metric
        :param bool log_event: If true, log the collected metric in the agent log
        """
        if log_event:
            from azurelinuxagent.common.version import AGENT_NAME
            message = "Metric {0}/{1} [{2}] = {3}".format(
                category, counter, instance, value)
            _log_event(AGENT_NAME, "METRIC", message, 0)

        event = TelemetryEvent(4, "69B669B9-4AF8-4C50-BDC4-6006FA76E975")
        event.parameters.append(TelemetryEventParam('Category', category))
        event.parameters.append(TelemetryEventParam('Counter', counter))
        event.parameters.append(TelemetryEventParam('Instance', instance))
        event.parameters.append(TelemetryEventParam('Value', value))

        self.add_default_parameters_to_event(event)
        data = get_properties(event)
        try:
            self.save_event(json.dumps(data))
        except EventError as e:
            logger.error("{0}", e)
Exemplo n.º 3
0
    def add_metric(self, category, counter, instance, value, log_event=False):
        """
        Create and save an event which contains a telemetry event.

        :param str category: The category of metric (e.g. "cpu", "memory")
        :param str counter: The specific metric within the category (e.g. "%idle")
        :param str instance: For instanced metrics, the instance identifier (filesystem name, cpu core#, etc.)
        :param value: Value of the metric
        :param bool log_event: If true, log the collected metric in the agent log
        """
        if log_event:
            message = "Metric {0}/{1} [{2}] = {3}".format(category, counter, instance, value)
            _log_event(AGENT_NAME, "METRIC", message, 0)

        event = TelemetryEvent(TELEMETRY_METRICS_EVENT_ID, TELEMETRY_EVENT_PROVIDER_ID)
        event.parameters.append(TelemetryEventParam(GuestAgentPerfCounterEventsSchema.Category, str(category)))
        event.parameters.append(TelemetryEventParam(GuestAgentPerfCounterEventsSchema.Counter, str(counter)))
        event.parameters.append(TelemetryEventParam(GuestAgentPerfCounterEventsSchema.Instance, str(instance)))
        event.parameters.append(TelemetryEventParam(GuestAgentPerfCounterEventsSchema.Value, float(value)))
        self.add_common_event_parameters(event, datetime.utcnow())

        data = get_properties(event)
        try:
            self.save_event(json.dumps(data))
        except EventError as e:
            logger.periodic_error(logger.EVERY_FIFTEEN_MINUTES, "[PERIODIC] {0}".format(ustr(e)))
    def add_log_event(self, level, message):
        # By the time the message has gotten to this point it is formatted as
        #
        #   YYYY/MM/DD HH:mm:ss.fffffff LEVEL <text>.
        #
        # The timestamp and the level are redundant, and should be stripped.
        # The logging library does not schematize this data, so I am forced
        # to parse the message.  The format is regular, so the burden is low.

        parts = message.split(' ', 3)
        msg = parts[3] if len(parts) == 4 \
            else message

        event = TelemetryEvent(7, "FFF0196F-EE4C-4EAF-9AA5-776F622DEB4F")
        event.parameters.append(
            TelemetryEventParam('EventName', WALAEventOperation.Log))
        event.parameters.append(
            TelemetryEventParam('CapabilityUsed',
                                logger.LogLevel.STRINGS[level]))
        event.parameters.append(TelemetryEventParam('Context1', msg))
        event.parameters.append(TelemetryEventParam('Context2', ''))
        event.parameters.append(TelemetryEventParam('Context3', ''))

        self.add_default_parameters_to_event(event)
        data = get_properties(event)
        try:
            self.save_event(json.dumps(data))
        except EventError:
            pass
Exemplo n.º 5
0
    def add_common_event_parameters(self, event, event_timestamp):
        """
        This method is called for all events and ensures all telemetry fields are added before the event is sent out.
        Note that the event timestamp is saved in the OpcodeName field.
        """
        common_params = [
            TelemetryEventParam(CommonTelemetryEventSchema.GAVersion,
                                CURRENT_AGENT),
            TelemetryEventParam(CommonTelemetryEventSchema.ContainerId,
                                AgentGlobals.get_container_id()),
            TelemetryEventParam(
                CommonTelemetryEventSchema.OpcodeName,
                event_timestamp.strftime(logger.Logger.LogTimeFormatInUTC)),
            TelemetryEventParam(CommonTelemetryEventSchema.EventTid,
                                threading.current_thread().ident),
            TelemetryEventParam(CommonTelemetryEventSchema.EventPid,
                                os.getpid()),
            TelemetryEventParam(CommonTelemetryEventSchema.TaskName,
                                threading.current_thread().getName()),
            TelemetryEventParam(CommonTelemetryEventSchema.KeywordName, '')
        ]

        if event.eventId == TELEMETRY_EVENT_EVENT_ID and event.providerId == TELEMETRY_EVENT_PROVIDER_ID:
            # Currently only the GuestAgentExtensionEvents has these columns, the other tables dont have them so skipping
            # this data in those tables.
            common_params.extend([
                TelemetryEventParam(
                    GuestAgentExtensionEventsSchema.ExtensionType,
                    event.file_type),
                TelemetryEventParam(GuestAgentExtensionEventsSchema.IsInternal,
                                    False)
            ])

        event.parameters.extend(common_params)
        event.parameters.extend(self._common_parameters)
Exemplo n.º 6
0
def get_test_event(name="DummyExtension",
                   op="Unknown",
                   is_success=True,
                   duration=0,
                   version="foo",
                   evt_type="",
                   is_internal=False,
                   message="DummyMessage",
                   eventId=1):
    event = TelemetryEvent(eventId, "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
    event.parameters.append(
        TelemetryEventParam(GuestAgentExtensionEventsSchema.Name, name))
    event.parameters.append(
        TelemetryEventParam(GuestAgentExtensionEventsSchema.Version,
                            str(version)))
    event.parameters.append(
        TelemetryEventParam(GuestAgentExtensionEventsSchema.IsInternal,
                            is_internal))
    event.parameters.append(
        TelemetryEventParam(GuestAgentExtensionEventsSchema.Operation, op))
    event.parameters.append(
        TelemetryEventParam(GuestAgentExtensionEventsSchema.OperationSuccess,
                            is_success))
    event.parameters.append(
        TelemetryEventParam(GuestAgentExtensionEventsSchema.Message, message))
    event.parameters.append(
        TelemetryEventParam(GuestAgentExtensionEventsSchema.Duration,
                            duration))
    event.parameters.append(
        TelemetryEventParam(GuestAgentExtensionEventsSchema.ExtensionType,
                            evt_type))
    return event
Exemplo n.º 7
0
    def add_log_event(self, level, message):
        event = TelemetryEvent(TELEMETRY_LOG_EVENT_ID,
                               TELEMETRY_LOG_PROVIDER_ID)
        event.parameters.append(
            TelemetryEventParam('EventName', WALAEventOperation.Log))
        event.parameters.append(
            TelemetryEventParam('CapabilityUsed',
                                logger.LogLevel.STRINGS[level]))
        event.parameters.append(
            TelemetryEventParam('Context1', self._clean_up_message(message)))
        event.parameters.append(TelemetryEventParam('Context2', ''))
        event.parameters.append(TelemetryEventParam('Context3', ''))
        self._add_common_event_parameters(event, datetime.utcnow())

        data = get_properties(event)
        try:
            self.save_event(json.dumps(data))
        except EventError:
            pass
def parse_xml_param(param_node):
    name = getattrib(param_node, "Name")
    value_str = getattrib(param_node, "Value")
    attr_type = getattrib(param_node, "T")
    value = value_str
    if attr_type == 'mt:uint64':
        value = int(value_str)
    elif attr_type == 'mt:bool':
        value = bool(value_str)
    elif attr_type == 'mt:float64':
        value = float(value_str)
    return TelemetryEventParam(name, value)
Exemplo n.º 9
0
    def add_event(self,
                  name,
                  op=WALAEventOperation.Unknown,
                  is_success=True,
                  duration=0,
                  version=str(CURRENT_VERSION),
                  message="",
                  log_event=True):

        if (not is_success) and log_event:
            _log_event(name, op, message, duration, is_success=is_success)

        event = TelemetryEvent(TELEMETRY_EVENT_EVENT_ID,
                               TELEMETRY_EVENT_PROVIDER_ID)
        event.parameters.append(TelemetryEventParam('Name', str(name)))
        event.parameters.append(TelemetryEventParam('Version', str(version)))
        event.parameters.append(TelemetryEventParam('Operation', str(op)))
        event.parameters.append(
            TelemetryEventParam('OperationSuccess', bool(is_success)))
        event.parameters.append(TelemetryEventParam('Message', str(message)))
        event.parameters.append(TelemetryEventParam('Duration', int(duration)))
        self._add_common_event_parameters(event, datetime.utcnow())

        data = get_properties(event)
        try:
            self.save_event(json.dumps(data))
        except EventError as e:
            logger.periodic_error(logger.EVERY_FIFTEEN_MINUTES,
                                  "[PERIODIC] {0}".format(ustr(e)))
    def _replace_or_add_param_in_event(event, replace_or_add_params):
        for param in event.parameters:
            if param.name in replace_or_add_params:
                param.value = replace_or_add_params.pop(param.name)

        if not replace_or_add_params:
            # All values replaced, return
            return

        # Add the remaining params to the event
        for param_name in replace_or_add_params:
            event.parameters.append(
                TelemetryEventParam(param_name,
                                    replace_or_add_params[param_name]))
    def _get_event_data(message, name):
        event = TelemetryEvent(1, TestSendTelemetryEventsHandler._TEST_EVENT_PROVIDER_ID)
        event.parameters.append(TelemetryEventParam(GuestAgentExtensionEventsSchema.Name, name))
        event.parameters.append(TelemetryEventParam(GuestAgentExtensionEventsSchema.Version, str(CURRENT_VERSION)))
        event.parameters.append(TelemetryEventParam(GuestAgentExtensionEventsSchema.Operation, WALAEventOperation.Unknown))
        event.parameters.append(TelemetryEventParam(GuestAgentExtensionEventsSchema.OperationSuccess, True))
        event.parameters.append(TelemetryEventParam(GuestAgentExtensionEventsSchema.Message, message))
        event.parameters.append(TelemetryEventParam(GuestAgentExtensionEventsSchema.Duration, 0))

        data = get_properties(event)
        return json.dumps(data)
Exemplo n.º 12
0
    def _add_common_event_parameters(self, event, event_timestamp):
        """
        This method is called for all events and ensures all telemetry fields are added before the event is sent out.
        Note that the event timestamp is saved in the OpcodeName field.
        """
        common_params = [
            TelemetryEventParam('GAVersion', CURRENT_AGENT),
            TelemetryEventParam('ContainerId', GoalState.ContainerID),
            TelemetryEventParam(
                'OpcodeName',
                event_timestamp.strftime(u'%Y-%m-%dT%H:%M:%S.%fZ')),
            TelemetryEventParam('EventTid',
                                threading.current_thread().ident),
            TelemetryEventParam('EventPid', os.getpid()),
            TelemetryEventParam('TaskName',
                                threading.current_thread().getName()),
            TelemetryEventParam('KeywordName', ''),
            TelemetryEventParam('ExtensionType', event.file_type),
            TelemetryEventParam('IsInternal', False)
        ]

        event.parameters.extend(common_params)
        event.parameters.extend(self._common_parameters)
Exemplo n.º 13
0
    def _add_event(self, duration, evt_type, is_internal, is_success, message,
                   name, op, version, event_id):
        event = TelemetryEvent(event_id, TELEMETRY_EVENT_PROVIDER_ID)
        event.parameters.append(TelemetryEventParam('Name', name))
        event.parameters.append(TelemetryEventParam('Version', str(version)))
        event.parameters.append(TelemetryEventParam('IsInternal', is_internal))
        event.parameters.append(TelemetryEventParam('Operation', op))
        event.parameters.append(
            TelemetryEventParam('OperationSuccess', is_success))
        event.parameters.append(TelemetryEventParam('Message', message))
        event.parameters.append(TelemetryEventParam('Duration', duration))
        event.parameters.append(TelemetryEventParam('ExtensionType', evt_type))

        self.add_default_parameters_to_event(event)
        data = get_properties(event)
        try:
            self.save_event(json.dumps(data))
        except EventError as e:
            logger.periodic_error(logger.EVERY_FIFTEEN_MINUTES,
                                  "[PERIODIC] {0}".format(ustr(e)))
Exemplo n.º 14
0
def get_test_event(name="DummyExtension",
                   op="Unknown",
                   is_success=True,
                   duration=0,
                   version="foo",
                   evt_type="",
                   is_internal=False,
                   message="DummyMessage",
                   eventId=1):
    event = TelemetryEvent(eventId, "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
    event.parameters.append(TelemetryEventParam('Name', name))
    event.parameters.append(TelemetryEventParam('Version', str(version)))
    event.parameters.append(TelemetryEventParam('IsInternal', is_internal))
    event.parameters.append(TelemetryEventParam('Operation', op))
    event.parameters.append(TelemetryEventParam('OperationSuccess',
                                                is_success))
    event.parameters.append(TelemetryEventParam('Message', message))
    event.parameters.append(TelemetryEventParam('Duration', duration))
    event.parameters.append(TelemetryEventParam('ExtensionType', evt_type))
    return event
Exemplo n.º 15
0
    def _update_legacy_agent_event(self, event, event_creation_time):
        # Ensure that if an agent event is missing a field from the schema defined since 2.2.47, the missing fields
        # will be appended, ensuring the event schema is complete before the event is reported.
        new_event = TelemetryEvent()
        new_event.parameters = []
        self._add_common_event_parameters(new_event, event_creation_time)

        event_params = dict([(param.name, param.value)
                             for param in event.parameters])
        new_event_params = dict([(param.name, param.value)
                                 for param in new_event.parameters])

        missing_params = set(new_event_params.keys()).difference(
            set(event_params.keys()))
        params_to_add = []
        for param_name in missing_params:
            params_to_add.append(
                TelemetryEventParam(param_name, new_event_params[param_name]))

        event.parameters.extend(params_to_add)
    def add_sysinfo(self, event):
        """
        This method is called after parsing the event file in the events folder and before emitting it. This means
        all events, either coming from the agent or from the extensions, are passed through this method. The purpose
        is to add a static list of sys_info parameters such as VMName, Region, RAM, etc. If the sys_info parameters
        are already populated in the event, they will be overwritten by the sys_info values obtained from the agent.
        Since the ContainerId parameter is only populated on the fly for the agent events because it is not a static
        sys_info parameter, an event coming from an extension will not have it, so we explicitly add it.
        :param event: Event to be enriched with sys_info parameters
        :return: Event with all parameters added, ready to be reported
        """
        sysinfo_names = [v.name for v in self.sysinfo]
        final_parameters = []

        # Refer: azurelinuxagent.common.event.EventLogger.add_default_parameters_to_event for agent specific values.
        #
        # Default fields are only populated by Agent and not the extension. Agent will fill up any event if they don't
        # have the default params. Example: GAVersion and ContainerId are populated for agent events on the fly,
        # but not for extension events. Add it if it's missing.
        default_values = [("ContainerId", get_container_id_from_env()),
                          ("GAVersion", CURRENT_AGENT), ("OpcodeName", ""),
                          ("EventTid", 0), ("EventPid", 0), ("TaskName", ""),
                          ("KeywordName", "")]

        for param in event.parameters:
            # Discard any sys_info parameters already in the event, since they will be overwritten
            if param.name in sysinfo_names:
                continue
            final_parameters.append(param)

        # Add sys_info params populated by the agent
        final_parameters.extend(self.sysinfo)

        for default_value in default_values:
            if default_value[0] not in event:
                final_parameters.append(
                    TelemetryEventParam(default_value[0], default_value[1]))

        event.parameters = final_parameters
Exemplo n.º 17
0
    def add_default_parameters_to_event(event, set_default_values=False):
        # We write the GAVersion here rather than add it in azurelinuxagent.ga.monitor.MonitorHandler.add_sysinfo
        # as there could be a possibility of events being sent with newer version of the agent, rather than the agent
        # version generating the event.
        # Old behavior example: V1 writes the event on the disk and finds an update immediately, and updates. Now the
        # new monitor thread would pick up the events from the disk and send it with the CURRENT_AGENT, which would have
        # newer version of the agent. This causes confusion.
        #
        # ContainerId can change due to live migration and we want to preserve the container Id of the container writing
        # the event, rather than sending the event.
        # OpcodeName: This is used as the actual time of event generation.

        default_parameters = [("GAVersion", CURRENT_AGENT),
                              ('ContainerId', get_container_id_from_env()),
                              ('OpcodeName', datetime.utcnow().__str__()),
                              ('EventTid', threading.current_thread().ident),
                              ('EventPid', os.getpid()),
                              ("TaskName",
                               threading.current_thread().getName()),
                              ("KeywordName", '')]

        for param in default_parameters:
            event.parameters.append(TelemetryEventParam(param[0], param[1]))
Exemplo n.º 18
0
    def _get_event_data(duration,
                        is_success,
                        message,
                        name,
                        op,
                        version,
                        eventId=1):
        event = TelemetryEvent(eventId, "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
        event.parameters.append(TelemetryEventParam('Name', name))
        event.parameters.append(TelemetryEventParam('Version', str(version)))
        event.parameters.append(TelemetryEventParam('Operation', op))
        event.parameters.append(
            TelemetryEventParam('OperationSuccess', is_success))
        event.parameters.append(TelemetryEventParam('Message', message))
        event.parameters.append(TelemetryEventParam('Duration', duration))

        data = get_properties(event)
        return json.dumps(data)
Exemplo n.º 19
0
    def test_add_default_parameters_to_agent_event(self, patch_datetime, *args):
        patch_datetime.utcnow = Mock(return_value=datetime.strptime("2019-01-01 01:30:00",
                                                                    '%Y-%m-%d %H:%M:%S'))
        default_parameters_expected = {"GAVersion": CURRENT_AGENT,
                                       'ContainerId': "TEST_CONTAINER_ID",
                                       'OpcodeName': "2019-01-01 01:30:00",
                                       'EventTid': threading.current_thread().ident,
                                       'EventPid': 42,
                                       "TaskName": "HelloWorldTask",
                                       "KeywordName": ""}
        agent_param_list_empty = EventLogger.add_default_parameters_to_event([], set_values_for_agent=True)
        self._assert_default_params_get_correctly_added(agent_param_list_empty, default_parameters_expected)

        # When some values are already populated in the TelemetryEventParamList.
        agent_param_list_populated = [TelemetryEventParam('Name', "DummyExtension"),
                                      TelemetryEventParam('Version', CURRENT_VERSION),
                                      TelemetryEventParam('Operation', "DummyOperation"),
                                      TelemetryEventParam('OperationSuccess', True),
                                      TelemetryEventParam('Message', "TestMessage"),
                                      TelemetryEventParam('Duration', 10), TelemetryEventParam('ExtensionType', ''),
                                      TelemetryEventParam('OpcodeName', '')]
        agent_param_list_after_defaults_added = EventLogger.add_default_parameters_to_event(agent_param_list_populated,
                                                                                            set_values_for_agent=True)
        self._assert_default_params_get_correctly_added(agent_param_list_after_defaults_added,
                                                        default_parameters_expected)

        # When some values are already populated in the TelemetryEventParamList, along with some
        # default values already populated and it should be replaced, when set_values_for_agent=True
        agent_param_list_populated = [TelemetryEventParam('Name', "DummyExtension"),
                                      TelemetryEventParam('Version', CURRENT_VERSION),
                                      TelemetryEventParam('Operation', "DummyOperation"),
                                      TelemetryEventParam('OperationSuccess', True),
                                      TelemetryEventParam('Message', "TestMessage"),
                                      TelemetryEventParam('Duration', 10), TelemetryEventParam('ExtensionType', ''),
                                      TelemetryEventParam('OpcodeName', 'timestamp'),
                                      TelemetryEventParam('ContainerId', 'SOME-CONTAINER'),
                                      TelemetryEventParam('EventTid', 10101010), TelemetryEventParam('EventPid', 110),
                                      TelemetryEventParam('TaskName', 'Test-TaskName')]

        agent_param_list_after_defaults_added = EventLogger.add_default_parameters_to_event(agent_param_list_populated,
                                                                                            set_values_for_agent=True)
        self._assert_default_params_get_correctly_added(agent_param_list_after_defaults_added,
                                                        default_parameters_expected)
Exemplo n.º 20
0
    def test_add_default_parameters_to_extension_event(self, *args):
        default_parameters_expected = {"GAVersion": CURRENT_AGENT, 'ContainerId': "TEST_CONTAINER_ID", 'OpcodeName': "",
                                       'EventTid': 0, 'EventPid': 0, "TaskName": "", "KeywordName": ""}

        # When no values are populated in the TelemetryEventParamList.
        extension_param_list_empty = EventLogger.add_default_parameters_to_event([], set_values_for_agent=False)
        self._assert_default_params_get_correctly_added(extension_param_list_empty, default_parameters_expected)

        # When some values are already populated in the TelemetryEventParamList.
        extension_param_list_populated = [TelemetryEventParam('Name', "DummyExtension"),
                                          TelemetryEventParam('Version', CURRENT_VERSION),
                                          TelemetryEventParam('Operation', "DummyOperation"),
                                          TelemetryEventParam('OperationSuccess', True),
                                          TelemetryEventParam('Message', "TestMessage"),
                                          TelemetryEventParam('Duration', 10), TelemetryEventParam('ExtensionType', ''),
                                          TelemetryEventParam('OpcodeName', '')]
        extension_param_list_with_defaults = EventLogger.add_default_parameters_to_event(extension_param_list_populated,
                                                                                         set_values_for_agent=False)
        self._assert_default_params_get_correctly_added(extension_param_list_with_defaults, default_parameters_expected)

        parameters_expected = {"GAVersion": CURRENT_AGENT, 'ContainerId': "TEST_CONTAINER_ID", 'OpcodeName': "",
                               'EventTid': 100, 'EventPid': 10, "TaskName": "", "KeywordName": ""}

        # When some values are already populated in the TelemetryEventParamList.
        extension_param_list_populated = [TelemetryEventParam('Name', "DummyExtension"),
                                          TelemetryEventParam('Version', CURRENT_VERSION),
                                          TelemetryEventParam('Operation', "DummyOperation"),
                                          TelemetryEventParam('OperationSuccess', True),
                                          TelemetryEventParam('Message', "TestMessage"),
                                          TelemetryEventParam('Duration', 10),
                                          TelemetryEventParam('ExtensionType', ''),
                                          TelemetryEventParam('OpcodeName', ''),
                                          TelemetryEventParam('EventTid', 100),
                                          TelemetryEventParam('EventPid', 10)]
        extension_param_list_with_defaults = EventLogger.add_default_parameters_to_event(extension_param_list_populated,
                                                                                         set_values_for_agent=False)
        self._assert_default_params_get_correctly_added(extension_param_list_with_defaults,
                                                        parameters_expected)
Exemplo n.º 21
0
    def __init__(self):
        self.event_dir = None
        self.periodic_events = {}

        #
        # All events should have these parameters.
        #
        # The first set comes from the current OS and is initialized here. These values don't change during
        # the agent's lifetime.
        #
        # The next two sets come from the goal state and IMDS and must be explicitly initialized using
        # initialize_vminfo_common_parameters() once a protocol for communication with the host has been
        # created. Their values  don't change during the agent's lifetime. Note that we initialize these
        # parameters here using dummy values (*_UNINITIALIZED) since events sent to the host should always
        # match the schema defined for them in the telemetry pipeline.
        #
        # There is another set of common parameters that must be computed at the time the event is created
        # (e.g. the timestamp and the container ID); those are added to events (along with the parameters
        # below) in _add_common_event_parameters()
        #
        # Note that different kinds of events may also include other parameters; those are added by the
        # corresponding add_* method (e.g. add_metric for performance metrics).
        #
        self._common_parameters = []

        # Parameters from OS
        osutil = get_osutil()
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.OSVersion, EventLogger._get_os_version()))
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.ExecutionMode, AGENT_EXECUTION_MODE))
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.RAM, int(EventLogger._get_ram(osutil))))
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.Processors, int(EventLogger._get_processors(osutil))))

        # Parameters from goal state
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.TenantName, "TenantName_UNINITIALIZED"))
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.RoleName, "RoleName_UNINITIALIZED"))
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.RoleInstanceName, "RoleInstanceName_UNINITIALIZED"))
        #
        # # Parameters from IMDS
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.Location, "Location_UNINITIALIZED"))
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.SubscriptionId, "SubscriptionId_UNINITIALIZED"))
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.ResourceGroupName, "ResourceGroupName_UNINITIALIZED"))
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.VMId, "VMId_UNINITIALIZED"))
        self._common_parameters.append(TelemetryEventParam(CommonTelemetryEventSchema.ImageOrigin, 0))
    def init_sysinfo(self):
        osversion = "{0}:{1}-{2}-{3}:{4}".format(platform.system(),
                                                 DISTRO_NAME, DISTRO_VERSION,
                                                 DISTRO_CODE_NAME,
                                                 platform.release())
        self.sysinfo.append(TelemetryEventParam("OSVersion", osversion))
        self.sysinfo.append(
            TelemetryEventParam("ExecutionMode", AGENT_EXECUTION_MODE))

        try:
            ram = self.osutil.get_total_mem()
            processors = self.osutil.get_processor_cores()
            self.sysinfo.append(TelemetryEventParam("RAM", ram))
            self.sysinfo.append(TelemetryEventParam("Processors", processors))
        except OSUtilError as e:
            logger.warn("Failed to get system info: {0}", ustr(e))

        try:
            vminfo = self.protocol.get_vminfo()
            self.sysinfo.append(TelemetryEventParam("VMName", vminfo.vmName))
            self.sysinfo.append(
                TelemetryEventParam("TenantName", vminfo.tenantName))
            self.sysinfo.append(
                TelemetryEventParam("RoleName", vminfo.roleName))
            self.sysinfo.append(
                TelemetryEventParam("RoleInstanceName",
                                    vminfo.roleInstanceName))
        except ProtocolError as e:
            logger.warn("Failed to get system info: {0}", ustr(e))

        try:
            vminfo = self.imds_client.get_compute()
            self.sysinfo.append(
                TelemetryEventParam('Location', vminfo.location))
            self.sysinfo.append(
                TelemetryEventParam('SubscriptionId', vminfo.subscriptionId))
            self.sysinfo.append(
                TelemetryEventParam('ResourceGroupName',
                                    vminfo.resourceGroupName))
            self.sysinfo.append(TelemetryEventParam('VMId', vminfo.vmId))
            self.sysinfo.append(
                TelemetryEventParam('ImageOrigin', vminfo.image_origin))
        except (HttpError, ValueError) as e:
            logger.warn("failed to get IMDS info: {0}", ustr(e))