Debian Codegraph @

mistralclient/commands/v2/base.py

raw symbols SCIP
1 # Copyright 2014 - Mirantis, Inc.
2 # Copyright 2020 - Nokia Software.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15 #
16
17 import abc
18 import datetime
19 import textwrap
20
21 from osc_lib.command import command
22 from oslo_utils import timeutils
23
24
25 DEFAULT_LIMIT = 100
26
27
28 class MistralFormatter(metaclass=abc.ABCMeta):
29 COLUMNS = []
30
31 @classmethod
32 def fields(cls):
33 # Column should be a tuple:
34 # (<field name>, <field title>, <optional synthetic flag>)
35 # If the 3rd value is specified and it's True then
36 # the field is synthetic (calculated) and should not be requested
37 # from the API client.
38 return [c[0] for c in cls.COLUMNS if len(c) == 2 or not c[2]]
39
40 @classmethod
41 def headings(cls):
42 return [c[1] for c in cls.COLUMNS]
43
44 @classmethod
45 def format_list(cls, instance=None):
46 return cls.format(instance, lister=True)
47
48 @staticmethod
49 def format(instance=None, lister=False):
50 pass
51
52
53 class MistralLister(command.Lister, metaclass=abc.ABCMeta):
54 @abc.abstractmethod
55 def _get_format_function(self):
56 raise NotImplementedError
57
58 def get_parser(self, parsed_args):
59 parser = super(MistralLister, self).get_parser(parsed_args)
60
61 parser.add_argument(
62 '--marker',
63 type=str,
64 help='The last execution uuid of the previous page, displays list '
65 'of executions after "marker".',
66 default='',
67 nargs='?'
68 )
69 parser.add_argument(
70 '--limit',
71 type=int,
72 help='Maximum number of entries to return in a single result. ',
73 nargs='?'
74 )
75 parser.add_argument(
76 '--sort_keys',
77 help='Comma-separated list of sort keys to sort results by. '
78 'Default: created_at. '
79 'Example: mistral execution-list --sort_keys=id,description',
80 default='created_at',
81 nargs='?'
82 )
83 parser.add_argument(
84 '--sort_dirs',
85 help='Comma-separated list of sort directions. Default: asc. '
86 'Example: mistral execution-list --sort_keys=id,description '
87 '--sort_dirs=asc,desc',
88 default='asc',
89 nargs='?'
90 )
91 parser.add_argument(
92 '--filter',
93 dest='filters',
94 action='append',
95 help='Filters. Can be repeated.'
96 )
97
98 return parser
99
100 @abc.abstractmethod
101 def _get_resources(self, parsed_args):
102 """Gets a list of API resources (e.g. using client)."""
103 raise NotImplementedError
104
105 def _validate_parsed_args(self, parsed_args):
106 # No-op by default.
107 pass
108
109 def take_action(self, parsed_args):
110 self._validate_parsed_args(parsed_args)
111
112 f = self._get_format_function()
113
114 ret = self._get_resources(parsed_args)
115
116 if not isinstance(ret, list):
117 ret = [ret]
118
119 data = [f(r)[1] for r in ret]
120
121 if data:
122 return f()[0], data
123 else:
124 return f()
125
126
127 class MistralExecutionLister(MistralLister, metaclass=abc.ABCMeta):
128 def get_parser(self, parsed_args):
129 parser = super(MistralExecutionLister, self).get_parser(parsed_args)
130 parser.set_defaults(limit=DEFAULT_LIMIT)
131 parser.add_argument(
132 '--oldest',
133 help='Display the executions starting from the oldest entries '
134 'instead of the newest',
135 default=False,
136 action='store_true'
137 )
138
139 return parser
140
141 def take_action(self, parsed_args):
142 self._validate_parsed_args(parsed_args)
143
144 f = self._get_format_function()
145
146 reverse_results = False
147 if (parsed_args.marker == '' and parsed_args.sort_dirs == 'asc' and
148 parsed_args.sort_keys == 'created_at' and
149 not parsed_args.oldest):
150 reverse_results = True
151 parsed_args.sort_dirs = 'desc'
152
153 ret = self._get_resources(parsed_args)
154 if not isinstance(ret, list):
155 ret = [ret]
156
157 if reverse_results:
158 ret.reverse()
159
160 data = [f(r)[1] for r in ret]
161
162 if data:
163 return f()[0], data
164 else:
165 return f()
166
167
168 def cut(string, length=25):
169 if string and len(string) > length:
170 return "%s..." % string[:length]
171 else:
172 return string
173
174
175 def wrap(string, width=25):
176 if string and len(string) > width:
177 return textwrap.fill(string, width)
178 else:
179 return string
180
181
182 def get_filters(parsed_args):
183 filters = {}
184
185 if parsed_args.filters:
186 for f in parsed_args.filters:
187 arr = f.split('=')
188
189 if len(arr) != 2:
190 raise ValueError('Invalid filter: %s' % f)
191
192 filters[arr[0]] = arr[1]
193
194 return filters
195
196
197 def get_duration_str(start_dt_str, end_dt_str):
198 """Builds a human friendly duration string.
199
200 :param start_dt_str: Start date time as an ISO string.
201 :param end_dt_str: End date time as an ISO string. If empty, duration is
202 calculated from the current time.
203 :return: Duration(delta) string.
204 """
205 if not start_dt_str:
206 return ''
207
208 start_dt = datetime.datetime.strptime(start_dt_str, '%Y-%m-%d %H:%M:%S')
209
210 if end_dt_str:
211 end_dt = datetime.datetime.strptime(end_dt_str, '%Y-%m-%d %H:%M:%S')
212
213 return str(end_dt - start_dt)
214
215 delta_from_now = timeutils.utcnow() - start_dt
216
217 # If delta is too small then we won't show any value. It means that
218 # the corresponding process (e.g. an execution) just started.
219 if delta_from_now < datetime.timedelta(seconds=2):
220 return '...'
221
222 # Drop microseconds to decrease verbosity.
223 delta = (
224 delta_from_now
225 - datetime.timedelta(microseconds=delta_from_now.microseconds)
226 )
227
228 return "{}...".format(delta)