Debian Codegraph @

heatclient/common/utils.py

raw symbols SCIP
1 # Copyright 2012 OpenStack Foundation
2 # All Rights Reserved.
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 import base64
17 import logging
18 import os
19 import textwrap
20 import uuid
21
22 from oslo_serialization import jsonutils
23 from oslo_utils import encodeutils
24 import prettytable
25 from urllib import error
26 from urllib import parse
27 from urllib import request
28 import yaml
29
30 from heatclient._i18n import _
31 from heatclient import exc
32
33 LOG = logging.getLogger(__name__)
34
35
36 supported_formats = {
37 "json": lambda x: jsonutils.dumps(x, indent=2),
38 "yaml": yaml.safe_dump
39 }
40
41
42 def arg(*args, **kwargs):
43 """Decorator for CLI args.
44
45 Example:
46
47 >>> @arg("name", help="Name of the new entity")
48 ... def entity_create(args):
49 ... pass
50 """
51 def _decorator(func):
52 add_arg(func, *args, **kwargs)
53 return func
54 return _decorator
55
56
57 def env(*args, **kwargs):
58 """Returns the first environment variable set.
59
60 If all are empty, defaults to '' or keyword arg `default`.
61 """
62 for arg in args:
63 value = os.environ.get(arg)
64 if value:
65 return value
66 return kwargs.get('default', '')
67
68
69 def add_arg(func, *args, **kwargs):
70 """Bind CLI arguments to a shell.py `do_foo` function."""
71
72 if not hasattr(func, 'arguments'):
73 func.arguments = []
74
75 # NOTE(sirp): avoid dups that can occur when the module is shared across
76 # tests.
77 if (args, kwargs) not in func.arguments:
78 # Because of the semantics of decorator composition if we just append
79 # to the options list positional options will appear to be backwards.
80 func.arguments.insert(0, (args, kwargs))
81
82
83 def print_list(objs, fields, formatters=None, sortby_index=0,
84 mixed_case_fields=None, field_labels=None):
85 """Print a list of objects as a table, one row per object.
86
87 :param objs: iterable of :class:`Resource`
88 :param fields: attributes that correspond to columns, in order
89 :param formatters: `dict` of callables for field formatting
90 :param sortby_index: index of the field for sorting table rows
91 :param mixed_case_fields: fields corresponding to object attributes that
92 have mixed case names (e.g., 'serverId')
93 :param field_labels: Labels to use in the heading of the table, default to
94 fields.
95 """
96 formatters = formatters or {}
97 mixed_case_fields = mixed_case_fields or []
98 field_labels = field_labels or fields
99 if len(field_labels) != len(fields):
100 raise ValueError(_("Field labels list %(labels)s has different number "
101 "of elements than fields list %(fields)s"),
102 {'labels': field_labels, 'fields': fields})
103
104 if sortby_index is None:
105 kwargs = {}
106 else:
107 kwargs = {'sortby': field_labels[sortby_index]}
108 pt = prettytable.PrettyTable(field_labels)
109 pt.align = 'l'
110
111 for o in objs:
112 row = []
113 for field in fields:
114 if field in formatters:
115 row.append(formatters[field](o))
116 else:
117 if field in mixed_case_fields:
118 field_name = field.replace(' ', '_')
119 else:
120 field_name = field.lower().replace(' ', '_')
121 data = getattr(o, field_name, '')
122 row.append(data)
123 pt.add_row(row)
124
125 print(encodeutils.safe_encode(pt.get_string(**kwargs)).decode())
126
127
128 def link_formatter(links):
129 def format_link(link):
130 if 'rel' in link:
131 return "{} ({})".format(link.get('href', ''), link.get('rel', ''))
132 else:
133 return "%s" % (link.get('href', ''))
134 return '\n'.join(format_link(link) for link in links or [])
135
136
137 def resource_nested_identifier(rsrc):
138 nested_link = [link for link in rsrc.links or []
139 if link.get('rel') == 'nested']
140 if nested_link:
141 nested_href = nested_link[0].get('href')
142 nested_identifier = nested_href.split("/")[-2:]
143 return "/".join(nested_identifier)
144
145
146 def json_formatter(js):
147 return jsonutils.dumps(js, indent=2, ensure_ascii=False,
148 separators=(', ', ': '))
149
150
151 def yaml_formatter(js):
152 return yaml.safe_dump(js, default_flow_style=False)
153
154
155 def text_wrap_formatter(d):
156 return '\n'.join(textwrap.wrap(d or '', 55))
157
158
159 def newline_list_formatter(r):
160 return '\n'.join(r or [])
161
162
163 def print_dict(d, formatters=None):
164 formatters = formatters or {}
165 pt = prettytable.PrettyTable(['Property', 'Value'],
166 caching=False, print_empty=False)
167 pt.align = 'l'
168
169 for field in d:
170 if field in formatters:
171 pt.add_row([field, formatters[field](d[field])])
172 else:
173 pt.add_row([field, d[field]])
174 print(pt.get_string(sortby='Property'))
175
176
177 class EventLogContext:
178
179 def __init__(self):
180 # key is a stack id or the name of the nested stack, value is a tuple
181 # of the parent stack id, and the name of the resource in the parent
182 # stack
183 self.id_to_res_info = {}
184
185 def prepend_paths(self, resource_path, stack_id):
186 if stack_id not in self.id_to_res_info:
187 return
188 stack_id, res_name = self.id_to_res_info.get(stack_id)
189 if res_name in self.id_to_res_info:
190 # do a double lookup to skip the ugly stack name that doesn't
191 # correspond to an actual resource name
192 n_stack_id, res_name = self.id_to_res_info.get(res_name)
193 resource_path.insert(0, res_name)
194 self.prepend_paths(resource_path, n_stack_id)
195 elif res_name:
196 resource_path.insert(0, res_name)
197
198 def build_resource_name(self, event):
199 res_name = getattr(event, 'resource_name')
200
201 # Contribute this event to self.id_to_res_info to assist with
202 # future calls to build_resource_name
203
204 def get_stack_id():
205 if getattr(event, 'stack_id', None) is not None:
206 return event.stack_id
207 for link in getattr(event, 'links', []):
208 if link.get('rel') == 'stack':
209 if 'href' not in link:
210 return None
211 stack_link = link['href']
212 return stack_link.split('/')[-1]
213
214 stack_id = get_stack_id()
215 if not stack_id:
216 return res_name
217 phys_id = getattr(event, 'physical_resource_id', None)
218 status = getattr(event, 'resource_status', None)
219
220 is_stack_event = stack_id == phys_id
221 if is_stack_event:
222 # this is an event for a stack
223 self.id_to_res_info[stack_id] = (stack_id, res_name)
224 elif phys_id and status == 'CREATE_IN_PROGRESS':
225 # this might be an event for a resource which creates a stack
226 self.id_to_res_info[phys_id] = (stack_id, res_name)
227
228 # Now build this resource path based on previous calls to
229 # build_resource_name
230 resource_path = []
231 if res_name and not is_stack_event:
232 resource_path.append(res_name)
233 self.prepend_paths(resource_path, stack_id)
234
235 return '.'.join(resource_path)
236
237
238 def event_log_formatter(events, event_log_context=None):
239 """Return the events in log format."""
240 event_log = []
241 log_format = ("%(event_time)s "
242 "[%(rsrc_name)s]: %(rsrc_status)s %(rsrc_status_reason)s")
243
244 # It is preferable for a context to be passed in, but there might be enough
245 # events in this call to build a better resource name, so create a context
246 # anyway
247 if event_log_context is None:
248 event_log_context = EventLogContext()
249
250 for event in events:
251 rsrc_name = event_log_context.build_resource_name(event)
252
253 event_time = getattr(event, 'event_time', '')
254 log = log_format % {
255 'event_time': event_time.replace('T', ' '),
256 'rsrc_name': rsrc_name,
257 'rsrc_status': getattr(event, 'resource_status', ''),
258 'rsrc_status_reason': getattr(event, 'resource_status_reason', '')
259 }
260 event_log.append(log)
261
262 return "\n".join(event_log)
263
264
265 def print_update_list(lst, fields, formatters=None):
266 """Print the stack-update --dry-run output as a table.
267
268 This function is necessary to print the stack-update --dry-run
269 output, which contains additional information about the update.
270 """
271 formatters = formatters or {}
272 pt = prettytable.PrettyTable(fields, caching=False, print_empty=False)
273 pt.align = 'l'
274
275 for change in lst:
276 row = []
277 for field in fields:
278 if field in formatters:
279 row.append(formatters[field](change.get(field, None)))
280 else:
281 row.append(change.get(field, None))
282
283 pt.add_row(row)
284
285 print(encodeutils.safe_encode(pt.get_string()).decode())
286
287
288 def find_resource(manager, name_or_id):
289 """Helper for the _find_* methods."""
290 # first try to get entity as integer id
291 try:
292 if isinstance(name_or_id, int) or name_or_id.isdigit():
293 return manager.get(int(name_or_id))
294 except exc.NotFound:
295 pass
296
297 # now try to get entity as uuid
298 try:
299 uuid.UUID(str(name_or_id))
300 return manager.get(name_or_id)
301 except (ValueError, exc.NotFound):
302 pass
303
304 # finally try to find entity by name
305 try:
306 return manager.find(name=name_or_id)
307 except exc.NotFound:
308 msg = (
309 _("No %(name)s with a name or ID of "
310 "'%(name_or_id)s' exists.")
311 % {
312 'name': manager.resource_class.__name__.lower(),
313 'name_or_id': name_or_id
314 })
315 raise exc.CommandError(msg)
316
317
318 def format_parameters(params, parse_semicolon=True):
319 '''Reformat parameters into dict of format expected by the API.'''
320
321 if not params:
322 return {}
323
324 if parse_semicolon:
325 # expect multiple invocations of --parameters but fall back
326 # to ; delimited if only one --parameters is specified
327 if len(params) == 1:
328 params = params[0].split(';')
329
330 parameters = {}
331 for p in params:
332 try:
333 (n, v) = p.split(('='), 1)
334 except ValueError:
335 msg = _('Malformed parameter(%s). Use the key=value format.') % p
336 raise exc.CommandError(msg)
337
338 if n not in parameters:
339 parameters[n] = v
340 else:
341 if not isinstance(parameters[n], list):
342 parameters[n] = [parameters[n]]
343 parameters[n].append(v)
344
345 return parameters
346
347
348 def format_all_parameters(params, param_files,
349 template_file=None, template_url=None):
350 parameters = {}
351 parameters.update(format_parameters(params))
352 parameters.update(format_parameter_file(
353 param_files,
354 template_file,
355 template_url))
356 return parameters
357
358
359 def format_parameter_file(param_files, template_file=None,
360 template_url=None):
361 '''Reformat file parameters into dict of format expected by the API.'''
362 if not param_files:
363 return {}
364 params = format_parameters(param_files, False)
365
366 template_base_url = None
367 if template_file or template_url:
368 template_base_url = base_url_for_url(get_template_url(
369 template_file, template_url))
370
371 param_file = {}
372 for key, value in params.items():
373 param_file[key] = resolve_param_get_file(value,
374 template_base_url)
375 return param_file
376
377
378 def resolve_param_get_file(file, base_url):
379 if base_url and not base_url.endswith('/'):
380 base_url = base_url + '/'
381 str_url = parse.urljoin(base_url, file)
382 return read_url_content(str_url)
383
384
385 def format_output(output, format='yaml'):
386 """Format the supplied dict as specified."""
387 output_format = format.lower()
388 try:
389 return supported_formats[output_format](output)
390 except KeyError:
391 raise exc.HTTPUnsupported(_("The format(%s) is unsupported.")
392 % output_format)
393
394
395 def parse_query_url(url):
396 base_url, query_params = url.split('?')
397 return base_url, parse.parse_qs(query_params)
398
399
400 def get_template_url(template_file=None, template_url=None):
401 if template_file:
402 template_url = normalise_file_path_to_url(template_file)
403 return template_url
404
405
406 def read_url_content(url):
407 try:
408 content = request.urlopen(url).read()
409 except error.URLError:
410 raise exc.CommandError(_('Could not fetch contents for %s') % url)
411
412 if content:
413 try:
414 content.decode('utf-8')
415 except ValueError:
416 content = base64.encodebytes(content)
417 return content
418
419
420 def base_url_for_url(url):
421 parsed = parse.urlparse(url)
422 parsed_dir = os.path.dirname(parsed.path)
423 return parse.urljoin(url, parsed_dir)
424
425
426 def normalise_file_path_to_url(path):
427 if parse.urlparse(path).scheme:
428 return path
429 path = os.path.abspath(path)
430 return parse.urljoin('file:', request.pathname2url(path))
431
432
433 def get_response_body(resp):
434 body = resp.content
435 if 'application/json' in resp.headers.get('content-type', ''):
436 try:
437 body = resp.json()
438 except ValueError:
439 LOG.error('Could not decode response body as JSON')
440 else:
441 body = None
442 return body