From 954e475a6a0a12432ec325d7579460fabcf3f40a Mon Sep 17 00:00:00 2001
From: Thomas Herve <therve@redhat.com>
Date: Tue, 28 Mar 2017 15:19:00 +0200
Subject: [PATCH] Build event stack_name from links

When retrieving events from nested stacks, we used to do a query per
stack and thus get the stack that way. We changed it to do only one API
call, but didn't fix the way the stack name was set. We need to use the
event links to retrieve the stack name, instead of the root stack.

Closes-Bug: #1676896
Change-Id: I09ab1cc2c6aaab02036b124b1dfa561dd6132083
---
 heatclient/common/event_utils.py          | 12 +++++++++++-
 heatclient/tests/unit/test_event_utils.py |  5 +++--
 2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/heatclient/common/event_utils.py b/heatclient/common/event_utils.py
index df000f73..8551b56c 100644
--- a/heatclient/common/event_utils.py
+++ b/heatclient/common/event_utils.py
@@ -151,6 +151,15 @@ def _get_nested_events(hc, nested_depth, stack_id, event_args):
     return nested_events
 
 
+def _get_stack_name_from_links(event):
+    links = dict((l.get('rel'),
+                  l.get('href')) for l in getattr(event, 'links', []))
+    href = links.get('stack')
+    if not href:
+        return
+    return href.split('/stacks/', 1)[-1].split('/')[0]
+
+
 def _get_stack_events(hc, stack_id, event_args):
     event_args['stack_id'] = stack_id
     try:
@@ -160,9 +169,10 @@ def _get_stack_events(hc, stack_id, event_args):
         # just use the message that the server sent us.
         raise exc.CommandError(str(ex))
     else:
+        stack_name = stack_id.split("/")[0]
         # Show which stack the event comes from (for nested events)
         for e in events:
-            e.stack_name = stack_id.split("/")[0]
+            e.stack_name = _get_stack_name_from_links(e) or stack_name
         return events
 
 
diff --git a/heatclient/tests/unit/test_event_utils.py b/heatclient/tests/unit/test_event_utils.py
index a9e89122..b080e000 100644
--- a/heatclient/tests/unit/test_event_utils.py
+++ b/heatclient/tests/unit/test_event_utils.py
@@ -47,8 +47,9 @@ class ShellTestEventUtils(testtools.TestCase):
     @staticmethod
     def _mock_event(event_id, resource_id,
                     resource_status='CREATE_COMPLETE'):
-        ev_info = {"links": [{"href": "http://heat/foo", "rel": "self"},
-                             {"href": "http://heat/stacks/a", "rel": "stack"}],
+        ev_info = {"links": [
+                   {"href": "http://heat/foo", "rel": "self"},
+                   {"href": "http://heat/stacks/astack", "rel": "stack"}],
                    "logical_resource_id": resource_id,
                    "physical_resource_id": resource_id,
                    "resource_name": resource_id,