4 # Copyright (C) 2010, 2011 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 """Module for a simple query language
24 A query filter is always a list. The first item in the list is the operator
25 (e.g. C{[OP_AND, ...]}), while the other items depend on the operator. For
26 logic operators (e.g. L{OP_AND}, L{OP_OR}), they are subfilters whose results
27 are combined. Unary operators take exactly one other item (e.g. a subfilter for
28 L{OP_NOT} and a field name for L{OP_TRUE}). Binary operators take exactly two
29 operands, usually a field name and a value to compare against. Filters are
30 converted to callable functions by L{query._CompileFilter}.
35 import string # pylint: disable=W0402
38 import pyparsing as pyp
40 from ganeti import errors
41 from ganeti import netutils
42 from ganeti import utils
43 from ganeti import compat
46 # Logic operators with one or more operands, each of which is a filter on its
52 # Unary operators with exactly one operand
57 # Binary operators with exactly two operands, the field name and an
58 # operator-specific value
69 #: Characters used for detecting user-written filters (see L{_CheckFilter})
70 FILTER_DETECTION_CHARS = frozenset("()=/!~'\"\\<>" + string.whitespace)
72 #: Characters used to detect globbing filters (see L{_CheckGlobbing})
73 GLOB_DETECTION_CHARS = frozenset("*?")
76 def MakeSimpleFilter(namefield, values):
77 """Builds simple a filter.
79 @param namefield: Name of field containing item name
80 @param values: List of names
84 return [OP_OR] + [[OP_EQUAL, namefield, i] for i in values]
89 def _ConvertLogicOp(op):
90 """Creates parsing action function for logic operator.
93 @param op: Operator for data structure, e.g. L{OP_AND}
97 """Converts parser tokens to query operator structure.
100 @return: Query operator structure, e.g. C{[OP_AND, ["=", "foo", "bar"]]}
105 if len(operands) == 1:
108 # Build query operator structure
109 return [[op] + operands.asList()]
114 _KNOWN_REGEXP_DELIM = "/#^|"
115 _KNOWN_REGEXP_FLAGS = frozenset("si")
118 def _ConvertRegexpValue(_, loc, toks):
119 """Regular expression value for condition.
122 (regexp, flags) = toks[0]
124 # Ensure only whitelisted flags are used
125 unknown_flags = (frozenset(flags) - _KNOWN_REGEXP_FLAGS)
127 raise pyp.ParseFatalException("Unknown regular expression flags: '%s'" %
128 "".join(unknown_flags), loc)
131 re_flags = "(?%s)" % "".join(sorted(flags))
135 re_cond = re_flags + regexp
140 except re.error, err:
141 raise pyp.ParseFatalException("Invalid regular expression (%s)" % err, loc)
146 def BuildFilterParser():
147 """Builds a parser for query filter strings.
149 @rtype: pyparsing.ParserElement
152 field_name = pyp.Word(pyp.alphas, pyp.alphanums + "_/.")
155 num_sign = pyp.Word("-+", exact=1)
156 number = pyp.Combine(pyp.Optional(num_sign) + pyp.Word(pyp.nums))
157 number.setParseAction(lambda toks: int(toks[0]))
159 quoted_string = pyp.quotedString.copy().setParseAction(pyp.removeQuotes)
161 # Right-hand-side value
162 rval = (number | quoted_string)
165 bool_cond = field_name.copy()
166 bool_cond.setParseAction(lambda (fname, ): [[OP_TRUE, fname]])
168 # Simple binary conditions
178 binary_cond = (field_name + pyp.oneOf(binopstbl.keys()) + rval)
179 binary_cond.setParseAction(lambda (lhs, op, rhs): [[binopstbl[op], lhs, rhs]])
182 in_cond = (rval + pyp.Suppress("in") + field_name)
183 in_cond.setParseAction(lambda (value, field): [[OP_CONTAINS, field, value]])
186 not_in_cond = (rval + pyp.Suppress("not") + pyp.Suppress("in") + field_name)
187 not_in_cond.setParseAction(lambda (value, field): [[OP_NOT, [OP_CONTAINS,
190 # Regular expression, e.g. m/foobar/i
191 regexp_val = pyp.Group(pyp.Optional("m").suppress() +
192 pyp.MatchFirst([pyp.QuotedString(i, escChar="\\")
193 for i in _KNOWN_REGEXP_DELIM]) +
194 pyp.Optional(pyp.Word(pyp.alphas), default=""))
195 regexp_val.setParseAction(_ConvertRegexpValue)
196 regexp_cond = (field_name + pyp.Suppress("=~") + regexp_val)
197 regexp_cond.setParseAction(lambda (field, value): [[OP_REGEXP, field, value]])
199 not_regexp_cond = (field_name + pyp.Suppress("!~") + regexp_val)
200 not_regexp_cond.setParseAction(lambda (field, value):
201 [[OP_NOT, [OP_REGEXP, field, value]]])
203 # Globbing, e.g. name =* "*.site"
204 glob_cond = (field_name + pyp.Suppress("=*") + quoted_string)
205 glob_cond.setParseAction(lambda (field, value):
207 utils.DnsNameGlobPattern(value)]])
209 not_glob_cond = (field_name + pyp.Suppress("!*") + quoted_string)
210 not_glob_cond.setParseAction(lambda (field, value):
211 [[OP_NOT, [OP_REGEXP, field,
212 utils.DnsNameGlobPattern(value)]]])
214 # All possible conditions
215 condition = (binary_cond ^ bool_cond ^
216 in_cond ^ not_in_cond ^
217 regexp_cond ^ not_regexp_cond ^
218 glob_cond ^ not_glob_cond)
220 # Associativity operators
221 filter_expr = pyp.operatorPrecedence(condition, [
222 (pyp.Keyword("not").suppress(), 1, pyp.opAssoc.RIGHT,
223 lambda toks: [[OP_NOT, toks[0][0]]]),
224 (pyp.Keyword("and").suppress(), 2, pyp.opAssoc.LEFT,
225 _ConvertLogicOp(OP_AND)),
226 (pyp.Keyword("or").suppress(), 2, pyp.opAssoc.LEFT,
227 _ConvertLogicOp(OP_OR)),
230 parser = pyp.StringStart() + filter_expr + pyp.StringEnd()
231 parser.parseWithTabs()
233 # Originally C{parser.validate} was called here, but there seems to be some
234 # issue causing it to fail whenever the "not" operator is included above.
239 def ParseFilter(text, parser=None):
240 """Parses a query filter.
243 @param text: Query filter
244 @type parser: pyparsing.ParserElement
245 @param parser: Pyparsing object
249 logging.debug("Parsing as query filter: %s", text)
252 parser = BuildFilterParser()
255 return parser.parseString(text)[0]
256 except pyp.ParseBaseException, err:
257 raise errors.QueryFilterParseError("Failed to parse query filter"
258 " '%s': %s" % (text, err), err)
261 def _IsHostname(text):
262 """Checks if a string could be a hostname.
268 netutils.Hostname.GetNormalizedName(text)
269 except errors.OpPrereqError:
275 def _CheckFilter(text):
276 """CHecks if a string could be a filter.
281 return bool(frozenset(text) & FILTER_DETECTION_CHARS)
284 def _CheckGlobbing(text):
285 """Checks if a string could be a globbing pattern.
290 return bool(frozenset(text) & GLOB_DETECTION_CHARS)
293 def _MakeFilterPart(namefield, text):
294 """Generates filter for one argument.
297 if _CheckGlobbing(text):
298 return [OP_REGEXP, namefield, utils.DnsNameGlobPattern(text)]
300 return [OP_EQUAL, namefield, text]
303 def MakeFilter(args, force_filter, namefield=None):
304 """Try to make a filter from arguments to a command.
306 If the name could be a filter it is parsed as such. If it's just a globbing
307 pattern, e.g. "*.site", such a filter is constructed. As a last resort the
308 names are treated just as a plain name filter.
310 @type args: list of string
311 @param args: Arguments to command
312 @type force_filter: bool
313 @param force_filter: Whether to force treatment as a full-fledged filter
314 @type namefield: string
315 @param namefield: Name of field to use for simple filters (use L{None} for
318 @return: Query filter
321 if namefield is None:
325 (args and len(args) == 1 and _CheckFilter(args[0]))):
327 (filter_text, ) = args
328 except (TypeError, ValueError):
329 raise errors.OpPrereqError("Exactly one argument must be given as a"
332 result = ParseFilter(filter_text)
334 result = [OP_OR] + map(compat.partial(_MakeFilterPart, namefield), args)