|
| 1 | +import abc |
| 2 | + |
| 3 | +import six |
| 4 | +from halo import halo |
| 5 | + |
| 6 | +from gradient import clilogger as gradient_logger, exceptions |
| 7 | +from gradient.api_sdk import sdk_exceptions |
| 8 | +from gradient.commands.common import ListCommandMixin |
| 9 | + |
| 10 | + |
| 11 | +@six.add_metaclass(abc.ABCMeta) |
| 12 | +class _ClustersCommand(object): |
| 13 | + def __init__(self, cluster_client, logger_=gradient_logger.CliLogger()): |
| 14 | + self.client = cluster_client |
| 15 | + self.logger = logger_ |
| 16 | + |
| 17 | + @abc.abstractmethod |
| 18 | + def execute(self, **kwargs): |
| 19 | + pass |
| 20 | + |
| 21 | + |
| 22 | +class ListClustersCommand(ListCommandMixin, _ClustersCommand): |
| 23 | + WAITING_FOR_RESPONSE_MESSAGE = "Waiting for data..." |
| 24 | + |
| 25 | + def execute(self, **kwargs): |
| 26 | + return self._generate_data_table(**kwargs) |
| 27 | + |
| 28 | + def _get_instances(self, **kwargs): |
| 29 | + try: |
| 30 | + instances= self.client.list(**kwargs) |
| 31 | + except sdk_exceptions.GradientSdkError as e: |
| 32 | + raise exceptions.ReceivingDataFailedError(e) |
| 33 | + |
| 34 | + return instances |
| 35 | + |
| 36 | + def _get_table_data(self, objects): |
| 37 | + data = [("ID", "Name", "Type")] |
| 38 | + |
| 39 | + for cluster in objects: |
| 40 | + handle = cluster.id |
| 41 | + name = cluster.name |
| 42 | + type = cluster.type |
| 43 | + data.append((handle, name, type)) |
| 44 | + return data |
| 45 | + |
| 46 | + def _generate_data_table(self, **kwargs): |
| 47 | + limit = kwargs.get("limit") |
| 48 | + offset = kwargs.get("offset") |
| 49 | + next_iteration = True |
| 50 | + |
| 51 | + while next_iteration: |
| 52 | + with halo.Halo(text=self.WAITING_FOR_RESPONSE_MESSAGE, spinner="dots"): |
| 53 | + kwargs["offset"] = offset |
| 54 | + instances = self._get_instances( |
| 55 | + **kwargs |
| 56 | + ) |
| 57 | + if instances: |
| 58 | + table_data = self._get_table_data(instances) |
| 59 | + table_str = self._make_list_table(table_data) + "\n" |
| 60 | + else: |
| 61 | + table_str = "No data found" |
| 62 | + |
| 63 | + if len(instances) < limit: |
| 64 | + next_iteration = False |
| 65 | + |
| 66 | + yield table_str, next_iteration |
| 67 | + offset += limit |
| 68 | + |
| 69 | + |
0 commit comments