Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove enum _UpdateType and retry fetching goal state #2018

Merged
merged 3 commits into from
Sep 24, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 58 additions & 46 deletions azurelinuxagent/common/protocol/goal_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from azurelinuxagent.common.AgentGlobals import AgentGlobals
from azurelinuxagent.common.datacontract import set_properties
from azurelinuxagent.common.event import add_event, WALAEventOperation
from azurelinuxagent.common.exception import ProtocolError
from azurelinuxagent.common.future import ustr
from azurelinuxagent.common.protocol.restapi import Cert, CertList, Extension, ExtHandler, ExtHandlerList, \
ExtHandlerVersionUri, RemoteAccessUser, RemoteAccessUsersList, \
Expand All @@ -42,9 +43,10 @@
TRANSPORT_PRV_FILE_NAME = "TransportPrivate.pem"


class GoalState(object): # pylint: disable=R0902

def __init__(self, wire_client, full_goal_state=False, base_incarnation=None):
# too-many-instance-attributes<R0902> Disabled: The goal state consists of a good number of properties
class GoalState(object): # pylint: disable=R0902
# too-many-branches<R0912> Disable: Branches are sequential, not nested
def __init__(self, wire_client, full_goal_state=False, base_incarnation=None): # pylint: disable=R0912
"""
Fetches the goal state using the given wire client.

Expand All @@ -58,42 +60,46 @@ def __init__(self, wire_client, full_goal_state=False, base_incarnation=None):
directly.

"""
uri = GOAL_STATE_URI.format(wire_client.get_endpoint())
self.xml_text = wire_client.fetch_config(uri, wire_client.get_header())
xml_doc = parse_doc(self.xml_text)

self.incarnation = findtext(xml_doc, "Incarnation")
self.expected_state = findtext(xml_doc, "ExpectedState")
role_instance = find(xml_doc, "RoleInstance")
self.role_instance_id = findtext(role_instance, "InstanceId")
role_config = find(role_instance, "Configuration")
self.role_config_name = findtext(role_config, "ConfigName")
container = find(xml_doc, "Container")
self.container_id = findtext(container, "ContainerId")
lbprobe_ports = find(xml_doc, "LBProbePorts")
self.load_balancer_probe_port = findtext(lbprobe_ports, "Port")

AgentGlobals.update_container_id(self.container_id)

fetch_full_goal_state = False
if full_goal_state:
fetch_full_goal_state = True
reason = 'force update'
elif base_incarnation is not None and self.incarnation != base_incarnation:
fetch_full_goal_state = True
reason = 'new incarnation'

if not fetch_full_goal_state:
self.hosting_env = None
self.shared_conf = None
self.certs = None
self.ext_conf = None
self.remote_access = None
return

logger.info('Fetching new goal state [incarnation {0} ({1})]', self.incarnation, reason)
try:
uri = GOAL_STATE_URI.format(wire_client.get_endpoint())
self.xml_text = wire_client.fetch_config(uri, wire_client.get_header())
xml_doc = parse_doc(self.xml_text)

self.incarnation = findtext(xml_doc, "Incarnation")
self.expected_state = findtext(xml_doc, "ExpectedState")
role_instance = find(xml_doc, "RoleInstance")
self.role_instance_id = findtext(role_instance, "InstanceId")
role_config = find(role_instance, "Configuration")
self.role_config_name = findtext(role_config, "ConfigName")
container = find(xml_doc, "Container")
self.container_id = findtext(container, "ContainerId")
lbprobe_ports = find(xml_doc, "LBProbePorts")
self.load_balancer_probe_port = findtext(lbprobe_ports, "Port")

AgentGlobals.update_container_id(self.container_id)

fetch_full_goal_state = False
if full_goal_state:
fetch_full_goal_state = True
reason = 'force update'
elif base_incarnation is not None and self.incarnation != base_incarnation:
fetch_full_goal_state = True
reason = 'new incarnation'

if not fetch_full_goal_state:
self.hosting_env = None
self.shared_conf = None
self.certs = None
self.ext_conf = None
self.remote_access = None
return
except Exception as exception:
# We don't log the error here since fetching the goal state is done every few seconds
raise ProtocolError(msg="Error fetching goal state", inner=exception)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be useful to add a traceback here? Might be useful in figuring out what exactly failed when trying to fetch GS

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought you were adding the traceback to error messages? (one way to do that could be in the conversion to string of the base class for exceptions)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

btw - since this is just raising the exception, the traceback shouln't be added here, but in whoever handles the exception

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and another note:

one way to do that could be in the conversion to string of the base class for exceptions)

may lead to bad (but useful) formatting. An alternative would be to create a function in the logger to log an exception. That function could also add traceback for the inner exceptions.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought you were adding the traceback to error messages?

I was primarily talking about doing it on a case to case basis, but I like your idea better of adding it for every error.

An alternative would be to create a function in the logger to log an exception.

That would be useful for sure, maybe reuse the logger.error? But anyways not sure when I'll get time to work on that. For now do you wanna add the trace here until we have a better solution in place?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The trace should not be added here, that should be done at the place where the exception is handled.


try:
logger.info('Fetching new goal state [incarnation {0} ({1})]', self.incarnation, reason)

uri = findtext(xml_doc, "HostingEnvironmentConfig")
xml_text = wire_client.fetch_config(uri, wire_client.get_header())
self.hosting_env = HostingEnv(xml_text)
Expand Down Expand Up @@ -122,9 +128,9 @@ def __init__(self, wire_client, full_goal_state=False, base_incarnation=None):
else:
xml_text = wire_client.fetch_config(uri, wire_client.get_header_for_cert())
self.remote_access = RemoteAccess(xml_text)
except Exception as e: # pylint: disable=C0103
logger.warn("Fetching the goal state failed: {0}", ustr(e))
raise
except Exception as exception:
logger.warn("Fetching the goal state failed: {0}", ustr(exception))
raise ProtocolError(msg="Error fetching goal state", inner=exception)
larohra marked this conversation as resolved.
Show resolved Hide resolved
finally:
logger.info('Fetch goal state completed')

Expand All @@ -151,7 +157,8 @@ def fetch_full_goal_state_if_incarnation_different_than(wire_client, incarnation
return goal_state if goal_state.incarnation != incarnation else None


class HostingEnv(object): # pylint: disable=R0903
# too-few-public-methods<R0903> Disabled: This is just a data object that does not need any public methods
class HostingEnv(object): # pylint: disable=R0903
def __init__(self, xml_text):
self.xml_text = xml_text
xml_doc = parse_doc(xml_text)
Expand All @@ -163,12 +170,14 @@ def __init__(self, xml_text):
self.deployment_name = getattrib(deployment, "name")


class SharedConfig(object): # pylint: disable=R0903
# too-few-public-methods<R0903> Disabled: This is just a data object that does not need any public methods
class SharedConfig(object): # pylint: disable=R0903
def __init__(self, xml_text):
self.xml_text = xml_text


class Certificates(object): # pylint: disable=R0903
# too-few-public-methods<R0903> Disabled: This is just a data object that does not need any public methods
class Certificates(object): # pylint: disable=R0903
def __init__(self, xml_text): # pylint: disable=R0912,R0914
self.cert_list = CertList()

Expand Down Expand Up @@ -275,8 +284,10 @@ def _write_to_tmp_file(index, suffix, buf):
return file_name


class ExtensionsConfig(object): # pylint: disable=R0903
def __init__(self, xml_text): # pylint: disable=R0914
# too-few-public-methods<R0903> Disabled: This is just a data object that does not need any public methods
class ExtensionsConfig(object): # pylint: disable=R0903
# too-many-locals<R0914> Disabled: The number of local variables is OK
def __init__(self, xml_text): # pylint: disable=R0914
self.xml_text = xml_text
self.ext_handlers = ExtHandlerList()
self.vmagent_manifests = VMAgentManifestList()
Expand Down Expand Up @@ -396,7 +407,8 @@ def _parse_plugin_settings(ext_handler, plugin_settings): # pylint: disable=R091
ext_handler.properties.extensions.append(ext)


class RemoteAccess(object): # pylint: disable=R0903
# too-few-public-methods<R0903> Disabled: This is just a data object that does not need any public methods
class RemoteAccess(object): # pylint: disable=R0903
"""
Object containing information about user accounts
"""
Expand Down
66 changes: 15 additions & 51 deletions azurelinuxagent/common/protocol/wire.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,27 +686,30 @@ def _fetch_response(self, uri, headers=None, use_proxy=None):
raise
return resp

# Type of update performed by _update_from_goal_state()
class _UpdateType(object): # pylint: disable=R0903
# Update the Host GA Plugin client (Container ID and RoleConfigName)
HostPlugin = 0
# Update the full goal state only if the incarnation has changed
GoalState = 1
# Update the full goal state unconditionally
GoalStateForced = 2

def update_host_plugin_from_goal_state(self):
"""
Fetches a new goal state and updates the Container ID and Role Config Name of the host plugin client
"""
self._update_from_goal_state(WireClient._UpdateType.HostPlugin)
goal_state = GoalState.fetch_goal_state(self)
self._update_host_plugin(goal_state.container_id, goal_state.role_config_name)

def update_goal_state(self, forced=False):
"""
Updates the goal state if the incarnation changed or if 'forced' is True
"""
self._update_from_goal_state(
WireClient._UpdateType.GoalStateForced if forced else WireClient._UpdateType.GoalState)
try:
if self._goal_state is None or forced:
new_goal_state = GoalState.fetch_full_goal_state(self)
else:
new_goal_state = GoalState.fetch_full_goal_state_if_incarnation_different_than(self, self._goal_state.incarnation)

if new_goal_state is not None:
self._goal_state = new_goal_state
self._save_goal_state()
self._update_host_plugin(new_goal_state.container_id, new_goal_state.role_config_name)

except Exception as e: # pylint: disable=C0103
larohra marked this conversation as resolved.
Show resolved Hide resolved
raise ProtocolError("Error processing goal state: {0}".format(ustr(e)))

def try_update_goal_state(self):
"""
Expand All @@ -732,45 +735,6 @@ def try_update_goal_state(self):
return False
return True

def _update_from_goal_state(self, refresh_type):
"""
Fetches a new goal state and updates the internal state of the WireClient according to the requested 'refresh_type'
"""
max_retry = 3

for retry in range(1, max_retry + 1):
try:
if refresh_type == WireClient._UpdateType.HostPlugin:
goal_state = GoalState.fetch_goal_state(self)
self._update_host_plugin(goal_state.container_id, goal_state.role_config_name)
return

if self._goal_state is None or refresh_type == WireClient._UpdateType.GoalStateForced:
new_goal_state = GoalState.fetch_full_goal_state(self)
else:
new_goal_state = GoalState.fetch_full_goal_state_if_incarnation_different_than(self, self._goal_state.incarnation)

if new_goal_state is not None:
self._goal_state = new_goal_state
self._save_goal_state()
self._update_host_plugin(new_goal_state.container_id, new_goal_state.role_config_name)

return

except IOError as e: # pylint: disable=C0103
logger.warn("IOError processing goal state (attempt {0}/{1}) [{2}]", retry, max_retry, ustr(e))

except ResourceGoneError:
logger.info("Goal state is stale, re-fetching (attempt {0}/{1})", retry, max_retry)

except ProtocolError as e: # pylint: disable=C0103
logger.verbose("ProtocolError processing goal state (attempt {0}/{1}) [{2}]", retry, max_retry, ustr(e))

except Exception as e: # pylint: disable=C0103
logger.verbose("Exception processing goal state (attempt {0}/{1}) [{2}]", retry, max_retry, ustr(e))

raise ProtocolError("Exceeded max retry updating goal state")

def _update_host_plugin(self, container_id, role_config_name):
if self._host_plugin is not None:
self._host_plugin.update_container_id(container_id)
Expand Down