helpers.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """
  2. Helper functions
  3. """
  4. import itertools
  5. import logging as log
  6. from cloudbridge.base.resources import ServerPagedResultList
  7. def os_result_limit(provider, requested_limit=None):
  8. """
  9. Calculates the limit for OpenStack.
  10. """
  11. limit = requested_limit or provider.config.default_result_limit
  12. # fetch one more than the limit to help with paging.
  13. # i.e. if length(objects) is one more than the limit,
  14. # we know that the object has another page of results,
  15. # so we always request one extra record.
  16. log.debug("Limit of OpenStack: %s Requested Limit: %s",
  17. limit, requested_limit)
  18. return limit + 1
  19. def to_server_paged_list(provider, objects, limit=None):
  20. """
  21. A convenience function for wrapping a list of OpenStack native objects in
  22. a ServerPagedResultList. OpenStack
  23. initial list of objects. Thereafter, the return list is wrapped in a
  24. BaseResultList, enabling extra properties like
  25. `is_truncated` and `marker` to be accessed.
  26. """
  27. limit = limit or provider.config.default_result_limit
  28. is_truncated = len(objects) > limit
  29. next_token = objects[limit-1].id if is_truncated else None
  30. results = ServerPagedResultList(is_truncated,
  31. next_token,
  32. False)
  33. for obj in itertools.islice(objects, limit):
  34. results.append(obj)
  35. return results