Move deeper-indented code to a separate method
This is a follow-up patch of
During the review, it turns out that the logic is too deep and
we cannot add more "if" clause. This commit tries to address it.
@@ -155,7 +155,22 @@ class IndexView(tables.PagedTableMixin, tables.DataTableView):
# Loop through instances to get flavor info.
for instance in instances:
- if hasattr(instance, 'image'):
+ self._populate_image_info(instance, image_dict, volume_dict)
+
+ flavor_id = instance.flavor["id"]
+ if flavor_id in flavor_dict:
+ instance.full_flavor = flavor_dict[flavor_id]
+ else:
+ # If the flavor_id is not in flavor_dict,
+ # put info in the log file.
+ LOG.info('Unable to retrieve flavor "%s" for instance "%s".',
+ flavor_id, instance.id)
+
+ return instances
+
+ def _populate_image_info(self, instance, image_dict, volume_dict):
+ if not hasattr(instance, 'image'):
+ return
# Instance from image returns dict
if isinstance(instance.image, dict):
image_id = instance.image.get('id')
@@ -174,31 +189,23 @@ class IndexView(tables.PagedTableMixin, tables.DataTableView):
for attachment in volume.attachments
if attachment['server_id'] == instance.id
]
- # Sorting attached volumes by device name (eg '/dev/sda')
- instance_volumes.sort(key=lambda attach: attach['device'])
# While instance from volume is being created,
# it does not have volumes
- if instance_volumes:
+ if not instance_volumes:
+ return
+ # Sorting attached volumes by device name (eg '/dev/sda')
+ instance_volumes.sort(key=lambda attach: attach['device'])
# Getting volume object, which is as attached
# as the first device
boot_volume = volume_dict[instance_volumes[0]['id']]
- if (hasattr(boot_volume, "volume_image_metadata") and
- boot_volume.volume_image_metadata['image_id'] in
- image_dict):
- instance.image = image_dict[
- boot_volume.volume_image_metadata['image_id']
- ]
-
- flavor_id = instance.flavor["id"]
- if flavor_id in flavor_dict:
- instance.full_flavor = flavor_dict[flavor_id]
- else:
- # If the flavor_id is not in flavor_dict,
- # put info in the log file.
- LOG.info('Unable to retrieve flavor "%s" for instance "%s".',
- flavor_id, instance.id)
-
- return instances
+ if hasattr(boot_volume, "volume_image_metadata"):
+ image_id = boot_volume.volume_image_metadata['image_id']
+ try:
+ instance.image = image_dict[image_id]
+ except KeyError:
+ # KeyError occurs when volume was created from image and
+ # then this image is deleted.
+ pass
def process_non_api_filters(search_opts, non_api_filter_info):
