Skip to content

Commit

Permalink
read container id from environment variable
Browse files Browse the repository at this point in the history
  • Loading branch information
pgombar committed Sep 14, 2019
1 parent 01b56c1 commit c17db25
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 58 deletions.
3 changes: 3 additions & 0 deletions azurelinuxagent/common/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import azurelinuxagent.common.logger as logger
from azurelinuxagent.common.exception import EventError
from azurelinuxagent.common.future import ustr
from azurelinuxagent.common.protocol.wire import CONTAINER_ID
from azurelinuxagent.common.protocol.restapi import TelemetryEventParam, \
TelemetryEvent, \
get_properties
Expand Down Expand Up @@ -94,6 +95,7 @@ class WALAEventOperation:
WALAEventOperation.UnInstall,
]


class EventStatus(object):
EVENT_STATUS_FILE = "event_status.json"

Expand Down Expand Up @@ -277,6 +279,7 @@ def _add_event(self, duration, evt_type, is_internal, is_success, message, name,
event.parameters.append(TelemetryEventParam('Message', message))
event.parameters.append(TelemetryEventParam('Duration', duration))
event.parameters.append(TelemetryEventParam('ExtensionType', evt_type))
event.parameters.append(TelemetryEventParam('ContainerId', os.environ.get(CONTAINER_ID, None)))

data = get_properties(event)
try:
Expand Down
9 changes: 2 additions & 7 deletions azurelinuxagent/common/protocol/wire.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
AGENTS_MANIFEST_FILE_NAME = "{0}.{1}.agentsManifest"
TRANSPORT_CERT_FILE_NAME = "TransportCert.pem"
TRANSPORT_PRV_FILE_NAME = "TransportPrivate.pem"
CONTAINER_ID = "AZURE_GUEST_AGENT_CONTAINER_ID"

PROTOCOL_VERSION = "2012-11-30"
ENDPOINT_FINE_NAME = "WireServer"
Expand Down Expand Up @@ -112,7 +113,6 @@ def get_vminfo(self):
vminfo.tenantName = hosting_env.deployment_name
vminfo.roleName = hosting_env.role_name
vminfo.roleInstanceName = goal_state.role_instance_id
vminfo.containerId = goal_state.container_id
return vminfo

def get_certs(self):
Expand Down Expand Up @@ -840,12 +840,6 @@ def get_goal_state(self):
self.goal_state = GoalState(xml_text)
return self.goal_state

def get_container_id_from_goal_state(self):
if self.goal_state is None:
return None

return self.goal_state.container_id

def get_hosting_env(self):
if self.hosting_env is None:
local_file = os.path.join(conf.get_lib_dir(),
Expand Down Expand Up @@ -1358,6 +1352,7 @@ def parse(self, xml_text):
self.role_config_name = findtext(role_config, "ConfigName")
container = find(xml_doc, "Container")
self.container_id = findtext(container, "ContainerId")
os.environ[CONTAINER_ID] = self.container_id
self.remote_access_uri = findtext(container, "RemoteAccessInfo")
lbprobe_ports = find(xml_doc, "LBProbePorts")
self.load_balancer_probe_port = findtext(lbprobe_ports, "Port")
Expand Down
16 changes: 0 additions & 16 deletions azurelinuxagent/ga/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,6 @@ def init_sysinfo(self):
vminfo.roleName))
self.sysinfo.append(TelemetryEventParam("RoleInstanceName",
vminfo.roleInstanceName))
self.sysinfo.append(TelemetryEventParam("ContainerId",
vminfo.containerId))
except ProtocolError as e:
logger.warn("Failed to get system info: {0}", ustr(e))

Expand Down Expand Up @@ -245,7 +243,6 @@ def collect_and_send_events(self):
try:
event = parse_event(data_str)
self.add_sysinfo(event)
self.update_container_id(event)
event_list.events.append(event)
except (ValueError, ProtocolError) as e:
logger.warn("Failed to decode event file: {0}", ustr(e))
Expand Down Expand Up @@ -288,19 +285,6 @@ def add_sysinfo(self, event):
event.parameters.remove(param)
event.parameters.extend(self.sysinfo)

def update_container_id(self, event):
last_known_container_id = self.protocol.client.get_container_id_from_goal_state()
if last_known_container_id is None:
return

for i, param in enumerate(event.parameters):
if param.name == "ContainerId":
if param.value == last_known_container_id:
# No update needed
return
updated_parameter = TelemetryEventParam("ContainerId", last_known_container_id)
event.parameters[i] = updated_parameter

def send_imds_heartbeat(self):
"""
Send a health signal every IMDS_HEARTBEAT_PERIOD. The signal is 'Healthy' when we have
Expand Down
33 changes: 32 additions & 1 deletion tests/common/test_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
WALAEventOperation, elapsed_milliseconds
from azurelinuxagent.common.exception import EventError
from azurelinuxagent.common.future import ustr
from azurelinuxagent.common.protocol.wire import GoalState
from azurelinuxagent.common.utils.processutil import read_output
from azurelinuxagent.common.version import CURRENT_VERSION
from azurelinuxagent.ga.monitor import MonitorHandler
Expand All @@ -34,6 +35,36 @@


class TestEvent(AgentTestCase):
def test_add_event_should_read_container_id_from_process_environment(self):
tmp_file = os.path.join(self.tmp_dir, "tmp_file")

def patch_save_event(json_data):
fileutil.write_file(tmp_file, json_data)

with patch("azurelinuxagent.common.event.EventLogger.save_event", side_effect=patch_save_event):
# No container id is set
os.environ.pop(event.CONTAINER_ID, None)
event.add_event(name='dummy_name')
data = fileutil.read_file(tmp_file)
self.assertIn('{"name": "ContainerId", "value": null}', data)

# Container id is set as an environment variable explicitly
os.environ[event.CONTAINER_ID] = '424242'
event.add_event(name='dummy_name')
data = fileutil.read_file(tmp_file)
self.assertIn('{{"name": "ContainerId", "value": "{0}"}}'.format(os.environ[event.CONTAINER_ID]), data)

# Container id is set as an environment variable when parsing the goal state
xml_text = load_data("wire/goal_state.xml")
goal_state = GoalState(xml_text)

container_id = goal_state.container_id
event.add_event(name='dummy_name')
data = fileutil.read_file(tmp_file)
self.assertIn('{{"name": "ContainerId", "value": "{0}"}}'.format(container_id), data)

os.environ.pop(event.CONTAINER_ID)

def test_event_status_event_marked(self):
es = event.__event_status__

Expand Down Expand Up @@ -239,7 +270,7 @@ def test_save_event_message_with_non_ascii_characters(self):
event_str = MonitorHandler.collect_event(os.path.join(self.tmp_dir, tld_file))
event_json = json.loads(event_str)

self.assertEqual(len(event_json["parameters"]), 8)
self.assertEqual(len(event_json["parameters"]), 9)

for i in event_json["parameters"]:
if i["name"] == "Name":
Expand Down
9 changes: 8 additions & 1 deletion tests/ga/test_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@
from azurelinuxagent.ga.exthandlers import *
from azurelinuxagent.common.protocol.wire import WireProtocol, InVMArtifactsProfile

SLEEP = time.sleep


def mock_sleep(sec=0.01):
return SLEEP(sec)


def do_not_run_test():
return True
Expand Down Expand Up @@ -294,6 +300,7 @@ def tearDownClass(cls):
CGroupConfigurator.get_instance().disable()


@patch('time.sleep', side_effect=lambda _: mock_sleep(0.001))
@patch("azurelinuxagent.common.protocol.wire.CryptUtil")
@patch("azurelinuxagent.common.utils.restutil.http_get")
class TestExtension(ExtensionTestCase):
Expand All @@ -320,7 +327,7 @@ def _assert_no_handler_status(self, report_vm_status):
self.assertEquals(0, len(vm_status.vmAgent.extensionHandlers))
return

def _create_mock(self, test_data, mock_http_get, MockCryptUtil):
def _create_mock(self, test_data, mock_http_get, MockCryptUtil, *args):
"""Test enable/disable/uninstall of an extension"""
handler = get_exthandlers_handler()

Expand Down
35 changes: 2 additions & 33 deletions tests/ga/test_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,19 +97,16 @@ def test_add_sysinfo(self, *args):
tenant_name = 'dummy_tenant'
role_name = 'dummy_role'
role_instance_name = 'dummy_role_instance'
container_id = 'dummy_container_id'

vm_name_param = "VMName"
tenant_name_param = "TenantName"
role_name_param = "RoleName"
role_instance_name_param = "RoleInstanceName"
container_id_param = "ContainerId"

sysinfo = [TelemetryEventParam(vm_name_param, vm_name),
TelemetryEventParam(tenant_name_param, tenant_name),
TelemetryEventParam(role_name_param, role_name),
TelemetryEventParam(role_instance_name_param, role_instance_name),
TelemetryEventParam(container_id_param, container_id)]
TelemetryEventParam(role_instance_name_param, role_instance_name)]
monitor_handler.sysinfo = sysinfo
monitor_handler.add_sysinfo(event)

Expand All @@ -130,36 +127,8 @@ def test_add_sysinfo(self, *args):
elif p.name == role_instance_name_param:
self.assertEqual(role_instance_name, p.value)
counter += 1
elif p.name == container_id_param:
self.assertEqual(container_id, p.value)
counter += 1

self.assertEqual(5, counter)

def test_update_container_id(self, *args):
old_container_id = "old_container_id"
new_container_id = "new_container_id"

event = TelemetryEvent()
event.parameters.append(TelemetryEventParam("ContainerId", old_container_id))
event.parameters.append(TelemetryEventParam("Message", "dummy message"))

monitor_handler = get_monitor_handler()
monitor_handler.protocol = WireProtocol("foo.bar")

with patch("azurelinuxagent.common.protocol.wire.WireClient.get_container_id_from_goal_state",
return_value=None):
monitor_handler.update_container_id(event)
for p in event.parameters:
if p.name == "ContainerId":
self.assertEquals(p.value, old_container_id)

with patch("azurelinuxagent.common.protocol.wire.WireClient.get_container_id_from_goal_state",
return_value=new_container_id):
monitor_handler.update_container_id(event)
for p in event.parameters:
if p.name == "ContainerId":
self.assertEquals(p.value, new_container_id)
self.assertEqual(4, counter)

@patch("azurelinuxagent.ga.monitor.MonitorHandler.send_telemetry_heartbeat")
@patch("azurelinuxagent.ga.monitor.MonitorHandler.collect_and_send_events")
Expand Down

0 comments on commit c17db25

Please sign in to comment.