| 1 |
# |
| 2 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 3 |
# not use this file except in compliance with the License. You may obtain |
| 4 |
# a copy of the License at |
| 5 |
# |
| 6 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
# |
| 8 |
# Unless required by applicable law or agreed to in writing, software |
| 9 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 10 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 11 |
# License for the specific language governing permissions and limitations |
| 12 |
# under the License. |
| 13 |
import re |
| 14 |
from urllib import parse as urllib_parse |
| 15 |
|
| 16 |
import pyparsing as pp |
| 17 |
|
| 18 |
uninary_operators = ("not", ) |
| 19 |
binary_operator = (">=", "<=", "!=", ">", "<", "=", "==", "eq", "ne", |
| 20 |
"lt", "gt", "ge", "le") |
| 21 |
multiple_operators = ("and", "or") |
| 22 |
|
| 23 |
operator = pp.Regex("|".join(binary_operator)) |
| 24 |
null = pp.Regex("None|none|null").setParseAction(pp.replaceWith(None)) |
| 25 |
boolean = "False|True|false|true" |
| 26 |
boolean = pp.Regex(boolean).setParseAction(lambda t: t[0].lower() == "true") |
| 27 |
hex_string = lambda n: pp.Word(pp.hexnums, exact=n) # noqa: E731 |
| 28 |
uuid = pp.Combine(hex_string(8) + ("-" + hex_string(4)) * 3 + |
| 29 |
"-" + hex_string(12)) |
| 30 |
number = r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?" |
| 31 |
number = pp.Regex(number).setParseAction(lambda t: float(t[0])) |
| 32 |
identifier = pp.Word(pp.alphas, pp.alphanums + "_") |
| 33 |
quoted_string = pp.QuotedString('"') | pp.QuotedString("'") |
| 34 |
comparison_term = pp.Forward() |
| 35 |
in_list = pp.Group(pp.Suppress('[') + |
| 36 |
pp.Optional(pp.delimitedList(comparison_term)) + |
| 37 |
pp.Suppress(']'))("list") |
| 38 |
comparison_term << (null | boolean | uuid | identifier | number | |
| 39 |
quoted_string) |
| 40 |
condition = pp.Group(comparison_term + operator + comparison_term) |
| 41 |
|
| 42 |
expr = pp.infixNotation(condition, [ |
| 43 |
("not", 1, pp.opAssoc.RIGHT, ), |
| 44 |
("and", 2, pp.opAssoc.LEFT, ), |
| 45 |
("or", 2, pp.opAssoc.LEFT, ), |
| 46 |
]) |
| 47 |
|
| 48 |
OP_LOOKUP = {'!=': 'ne', |
| 49 |
'>=': 'ge', |
| 50 |
'<=': 'le', |
| 51 |
'>': 'gt', |
| 52 |
'<': 'lt', |
| 53 |
'=': 'eq'} |
| 54 |
|
| 55 |
OP_LOOKUP_KEYS = '|'.join(sorted(OP_LOOKUP.keys(), key=len, reverse=True)) |
| 56 |
OP_SPLIT_RE = re.compile(r'(%s)' % OP_LOOKUP_KEYS) |
| 57 |
|
| 58 |
|
| 59 |
def _parsed_query2dict(parsed_query): |
| 60 |
result = None |
| 61 |
while parsed_query: |
| 62 |
part = parsed_query.pop() |
| 63 |
if part in binary_operator: |
| 64 |
result = {part: {parsed_query.pop(): result}} |
| 65 |
|
| 66 |
elif part in multiple_operators: |
| 67 |
if result.get(part): |
| 68 |
result[part].append( |
| 69 |
_parsed_query2dict(parsed_query.pop())) |
| 70 |
else: |
| 71 |
result = {part: [result]} |
| 72 |
|
| 73 |
elif part in uninary_operators: |
| 74 |
result = {part: result} |
| 75 |
elif isinstance(part, pp.ParseResults): |
| 76 |
kind = part.getName() |
| 77 |
if kind == "list": |
| 78 |
res = part.asList() |
| 79 |
else: |
| 80 |
res = _parsed_query2dict(part) |
| 81 |
if result is None: |
| 82 |
result = res |
| 83 |
elif isinstance(result, dict): |
| 84 |
list(result.values())[0].append(res) |
| 85 |
else: |
| 86 |
result = part |
| 87 |
return result |
| 88 |
|
| 89 |
|
| 90 |
def search_query_builder(query): |
| 91 |
parsed_query = expr.parseString(query)[0] |
| 92 |
return _parsed_query2dict(parsed_query) |
| 93 |
|
| 94 |
|
| 95 |
def list2cols(cols, objs): |
| 96 |
return cols, [tuple([o[k] for k in cols]) |
| 97 |
for o in objs] |
| 98 |
|
| 99 |
|
| 100 |
def format_string_list(objs, field): |
| 101 |
objs[field] = ", ".join(objs[field]) |
| 102 |
|
| 103 |
|
| 104 |
def format_dict_list(objs, field): |
| 105 |
objs[field] = "\n".join( |
| 106 |
"- " + ", ".join(f"{k}: {v}" |
| 107 |
for k, v in elem.items()) |
| 108 |
for elem in objs[field]) |
| 109 |
|
| 110 |
|
| 111 |
def format_move_dict_to_root(obj, field): |
| 112 |
for attr in obj[field]: |
| 113 |
obj[f"{field}/{attr}"] = obj[field][attr] |
| 114 |
del obj[field] |
| 115 |
|
| 116 |
|
| 117 |
def format_archive_policy(ap): |
| 118 |
format_dict_list(ap, "definition") |
| 119 |
format_string_list(ap, "aggregation_methods") |
| 120 |
|
| 121 |
|
| 122 |
def dict_from_parsed_args(parsed_args, attrs): |
| 123 |
d = {} |
| 124 |
for attr in attrs: |
| 125 |
if attr == "metric": |
| 126 |
if parsed_args.metrics: |
| 127 |
value = parsed_args.metrics[0] |
| 128 |
else: |
| 129 |
value = None |
| 130 |
else: |
| 131 |
value = getattr(parsed_args, attr) |
| 132 |
if value is not None: |
| 133 |
if value == [""]: |
| 134 |
# NOTE(jake): As options like --alarm-actions is an array, |
| 135 |
# their value can be array with empty string if user set option |
| 136 |
# to ''. In this case we set it to None here so that a None |
| 137 |
# value gets sent to API. |
| 138 |
d[attr] = None |
| 139 |
else: |
| 140 |
d[attr] = value |
| 141 |
return d |
| 142 |
|
| 143 |
|
| 144 |
def dict_to_querystring(objs): |
| 145 |
return "&".join([f"{k}={v}" |
| 146 |
for k, v in objs.items() |
| 147 |
if v is not None]) |
| 148 |
|
| 149 |
|
| 150 |
def cli_to_array(cli_query): |
| 151 |
"""Convert CLI list of queries to the Python API format. |
| 152 |
|
| 153 |
This will convert the following: |
| 154 |
"this<=34;that=string::foo" |
| 155 |
to |
| 156 |
"[{field=this,op=le,value=34,type=''}, |
| 157 |
{field=that,op=eq,value=foo,type=string}]" |
| 158 |
|
| 159 |
""" |
| 160 |
|
| 161 |
opts = [] |
| 162 |
queries = cli_query.split(';') |
| 163 |
for q in queries: |
| 164 |
try: |
| 165 |
field, q_operator, type_value = OP_SPLIT_RE.split(q, maxsplit=1) |
| 166 |
except ValueError: |
| 167 |
raise ValueError('Invalid or missing operator in query %(q)s,' |
| 168 |
'the supported operators are: %(k)s' % |
| 169 |
{'q': q, 'k': OP_LOOKUP.keys()}) |
| 170 |
if not field: |
| 171 |
raise ValueError('Missing field in query %s' % q) |
| 172 |
if not type_value: |
| 173 |
raise ValueError('Missing value in query %s' % q) |
| 174 |
opt = dict(field=field, op=OP_LOOKUP[q_operator]) |
| 175 |
|
| 176 |
if '::' not in type_value: |
| 177 |
opt['type'], opt['value'] = '', type_value |
| 178 |
else: |
| 179 |
opt['type'], _, opt['value'] = type_value.partition('::') |
| 180 |
|
| 181 |
if opt['type'] and opt['type'] not in ( |
| 182 |
'string', 'integer', 'float', 'datetime', 'boolean'): |
| 183 |
err = ('Invalid value type %(type)s, the type of value' |
| 184 |
'should be one of: integer, string, float, datetime,' |
| 185 |
' boolean.' % opt) |
| 186 |
raise ValueError(err) |
| 187 |
opts.append(opt) |
| 188 |
return opts |
| 189 |
|
| 190 |
|
| 191 |
def get_pagination_options(limit=None, marker=None, sorts=None): |
| 192 |
options = [] |
| 193 |
if limit: |
| 194 |
options.append("limit=%d" % limit) |
| 195 |
if marker: |
| 196 |
options.append("marker=%s" % urllib_parse.quote(marker)) |
| 197 |
for sort in sorts or []: |
| 198 |
options.append("sort=%s" % urllib_parse.quote(sort)) |
| 199 |
return "&".join(options) |
| 200 |
|
| 201 |
|
| 202 |
def get_client(obj): |
| 203 |
if hasattr(obj.app, 'client_manager'): |
| 204 |
# NOTE(liusheng): cliff objects loaded by OSC |
| 205 |
return obj.app.client_manager.alarming |
| 206 |
else: |
| 207 |
# TODO(liusheng): Remove this when OSC is able |
| 208 |
# to install the aodh client binary itself |
| 209 |
return obj.app.client |