Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
narrieta@microsoft committed Aug 22, 2024
1 parent 4bf7a6b commit 5745ca9
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 43 deletions.
46 changes: 41 additions & 5 deletions azurelinuxagent/common/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,10 +326,10 @@ def report_dropped_events_error(count, errors, operation_name):
report_dropped_events_error(self.__unicode_error_count, self.__unicode_errors, self.__unicode_error_event)

@staticmethod
def _update_errors_and_get_count(error_count, errors, error):
def _update_errors_and_get_count(error_count, errors, error_msg):
error_count += 1
if len(errors) < CollectOrReportEventDebugInfo.__MAX_ERRORS_TO_REPORT:
errors.add("{0}: {1}".format(ustr(error), traceback.format_exc()))
errors.add("{0}: {1}".format(ustr(error_msg), traceback.format_exc()))
return error_count

def update_unicode_error(self, unicode_err):
Expand Down Expand Up @@ -675,7 +675,23 @@ def initialize_event_logger_vminfo_common_parameters(protocol, reporter=__event_


def add_event(name=AGENT_NAME, op=WALAEventOperation.Unknown, is_success=True, duration=0, version=str(CURRENT_VERSION),
message="", log_event=True, reporter=__event_logger__):
message="", log_level=None, log_event=True, reporter=__event_logger__):
"""
NOTES:
* If log_event is True and is_success is False, the event is logged in the agent's log using this format: "Event: name={0}, op={1}, message={2}, duration={3}".
This usage is kept only for backwards compatibility, prefer the use of log_level over log_event and is_success.
* If log_level is provided, the event is logged using the provided logger.LogLevel. The log_event parameter is set to False and the is_success parameter is
set to False if the log level is ERROR or WARNING, or True otherwise
See also verbose(), info(), warning(), error()
"""
if log_level is not None:
logger.log(log_level, "{0}".format(message))
log_event = False
is_success = log_level == logger.LogLevel.WARNING or log_level == logger.LogLevel.ERROR
message = message if log_level != logger.LogLevel.WARNING else "[WARNING] {0}".format(message)

if reporter.event_dir is None:
logger.warn("Cannot add event -- Event reporter is not initialized.")
_log_event(name, op, message, duration, is_success=is_success)
Expand All @@ -688,6 +704,26 @@ def add_event(name=AGENT_NAME, op=WALAEventOperation.Unknown, is_success=True, d
log_event=log_event)


def verbose(op, message):
"""Convenience wrapper over add_event(log_level=logger.LogLevel.VERBOSE...)"""
add_event(op=op, message=message, log_level=logger.LogLevel.VERBOSE)


def info(op, message):
"""Convenience wrapper over add_event(log_level=logger.LogLevel.INFO...)"""
add_event(op=op, message=message, log_level=logger.LogLevel.INFO)


def warning(op, message):
"""Convenience wrapper over add_event(log_level=logger.LogLevel.WARNING...)"""
add_event(op=op, message=message, log_level=logger.LogLevel.WARNING)


def error(op, message):
"""Convenience wrapper over add_event(log_level=logger.LogLevel.ERROR...)"""
add_event(op=op, message=message, log_level=logger.LogLevel.ERROR)


def add_log_event(level, message, forced=False, reporter=__event_logger__):
"""
:param level: LoggerLevel of the log event
Expand Down Expand Up @@ -745,9 +781,9 @@ def dump_unhandled_err(name):
last_type = getattr(sys, 'last_type')
last_value = getattr(sys, 'last_value')
last_traceback = getattr(sys, 'last_traceback')
error = traceback.format_exception(last_type, last_value,
trace = traceback.format_exception(last_type, last_value,
last_traceback)
message = "".join(error)
message = "".join(trace)
add_event(name, is_success=False, message=message,
op=WALAEventOperation.UnhandledError)

Expand Down
26 changes: 12 additions & 14 deletions azurelinuxagent/ga/firewall_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import re

from azurelinuxagent.common import logger
from azurelinuxagent.common import event
from azurelinuxagent.common.event import add_event, WALAEventOperation
from azurelinuxagent.common.utils import shellutil

Expand Down Expand Up @@ -157,21 +158,18 @@ def remove(self):
self._execute_delete_command(command)

def remove_legacy_rule(self):
check_command = self._get_legacy_rule_command(self._get_check_command_option())
try:
check_command = self._get_legacy_rule_command(self._get_check_command_option())
try:
shellutil.run_command(check_command)
except CommandError as e:
if e.returncode == 1: # rule does not exist
return
logger.info("Found legacy firewall rule: {0}", check_command)

delete_command = self._get_legacy_rule_command(self._get_delete_command_option())
logger.info("Removing legacy firewall rule: {0}", delete_command)
self._execute_delete_command(delete_command)

except Exception as error:
logger.info("Unable to remove legacy firewall rule. Error: {0}".format(ustr(error)))
shellutil.run_command(check_command)
except CommandError as e:
if e.returncode == 1: # rule does not exist
logger.info("Did not find a legacy firewall rule: {0}", check_command)
return

logger.info("Found legacy firewall rule: {0}", check_command)
delete_command = self._get_legacy_rule_command(self._get_delete_command_option())
self._execute_delete_command(delete_command)
event.info(WALAEventOperation.Firewall, "Removed legacy firewall rule: {0}".format(delete_command))

def _execute_delete_command(self, command):
"""
Expand Down
38 changes: 14 additions & 24 deletions azurelinuxagent/ga/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@

from azurelinuxagent.common import conf
from azurelinuxagent.common import logger
from azurelinuxagent.common import event
from azurelinuxagent.common.utils import fileutil, textutil
from azurelinuxagent.common.agent_supported_feature import get_supported_feature_by_name, SupportedFeatureNames, \
get_agent_supported_features_list_for_crp
from azurelinuxagent.ga.cgroupconfigurator import CGroupConfigurator
from azurelinuxagent.common.event import add_event, initialize_event_logger_vminfo_common_parameters, \
WALAEventOperation, EVENTS_DIRECTORY
from azurelinuxagent.common.event import add_event, initialize_event_logger_vminfo_common_parameters, WALAEventOperation, EVENTS_DIRECTORY
from azurelinuxagent.common.exception import ExitException, AgentUpgradeExitException, AgentMemoryExceededException
from azurelinuxagent.ga.firewall_manager import FirewallManager, FirewallStateError
from azurelinuxagent.common.future import ustr
Expand Down Expand Up @@ -359,6 +359,7 @@ def run(self, debug=False):

from azurelinuxagent.ga.remoteaccess import get_remote_access_handler
remote_access_handler = get_remote_access_handler(protocol)

agent_update_handler = get_agent_update_handler(protocol)

self._ensure_no_orphans()
Expand Down Expand Up @@ -1076,45 +1077,34 @@ def _ensure_extension_telemetry_state_configured_properly(protocol):
def _initialize_firewall(wire_server_address):
try:
if not conf.enable_firewall():
logger.info("Skipping firewall initialization, since OS.EnableFirewall=False")
event.info(WALAEventOperation.Firewall, "Skipping firewall initialization, since OS.EnableFirewall=False")
return

firewall_manager = FirewallManager.create(wire_server_address)

firewall_manager.remove_legacy_rule()
try:
firewall_manager.remove_legacy_rule()
except Exception as error:
event.error(WALAEventOperation.Firewall, "Unable to remove legacy firewall rule. Error: {0}".format(ustr(error)))

try:
if firewall_manager.check():
msg = "The firewall rules for Azure Fabric are already setup:\n{0}".format(firewall_manager.get_state())
event.info(WALAEventOperation.Firewall, "The firewall rules for Azure Fabric are already setup:\n{0}".format(firewall_manager.get_state()))
else:
firewall_manager.setup()
msg = "Created firewall rules for Azure Fabric:\n{0}".format(firewall_manager.get_state())

logger.info(msg)
add_event(op=WALAEventOperation.Firewall, message=msg)

event.info(WALAEventOperation.Firewall, "Created firewall rules for Azure Fabric:\n{0}".format(firewall_manager.get_state()))
except FirewallStateError as e:
# Report the error and let the environment thread fix the firewall
msg = "The firewall rules for Azure Fabric are not setup correctly (the environment thread will fix it): {0}".format(ustr(e))
logger.warn("{0}", msg)
add_event(op=WALAEventOperation.Firewall, message=msg, is_success=False, log_event=False)
event.warning(WALAEventOperation.Firewall, "The firewall rules for Azure Fabric are not setup correctly (the environment thread will fix it): {0}".format(ustr(e)))

#
# Ensure firewall rules are persisted across reboots
#
logger.info("Setting up persistent firewall rules")
try:
PersistFirewallRulesHandler(dst_ip=wire_server_address).setup()
success = True
msg = "Persistent firewall rules setup successfully"
logger.info(msg)
event.info(WALAEventOperation.PersistFirewallRules, "Persistent firewall rules setup successfully")
except Exception as error:
success = False
msg = "Unable to setup the persistent firewall rules: {0}".format(ustr(error))
logger.error(msg)

add_event(op=WALAEventOperation.PersistFirewallRules, message=msg, is_success=success, log_event=False)
event.error(WALAEventOperation.PersistFirewallRules, "Unable to setup the persistent firewall rules: {0}".format(ustr(error)))

except Exception as e:
msg = "Error initializing firewall: {0}".format(ustr(e))
logger.error(msg)
event.error(WALAEventOperation.Firewall, "Error initializing firewall: {0}".format(ustr(e)))

0 comments on commit 5745ca9

Please sign in to comment.