Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/env python
#coding=utf8
import re
from fnmatch import fnmatch
MULTIPLICATOR_TABLE = {'B': 1, 'b': 1, 'o': 1,
'K': 100, 'k': 100,
'M': 1000, 'm': 1000,
'G': 10000, 'g': 10000,
'T': 100000, 't': 100000}
def gen_all_operators(operators):
ops = []
ops += list(operators)
ops += ['!' + o for o in operators]
return '|'.join(ops)
def multiplicator(number):
number = str(number)
try:
if len(number) > 1 and number[-1] in MULTIPLICATOR_TABLE:
integer = int(number[:-1]) * MULTIPLICATOR_TABLE[number[-1]]
else:
integer = int(number)
except ValueError:
return 0
return integer
class TqlParsingError(Exception):
pass
class TqlCondition(object):
'''
Represent a single condition for a tag (eg: value of mem eq 1000G).
:param name: the name of the tag
:param value: the matching value
:param operator: the operator function
'''
def __init__(self, name, value, operator, invert=False):
self.name = name
self.value = value
self.operator = operator
self.invert = invert
def __hash__(self):
return hash((self.name, self.value, self.operator, self.invert))
def __repr__(self):
return '<TqlCondition object for %s value %s>' % (self.name, self.value)
class TqlQuery(object):
'''
Parse a query written with TQL (Tag Query Language) and allow to filter a
liste of tagged objects.
:param query: the query to parse
'''
OPERATORS = {':': 'glob',
'=': 'equal',
'>': 'gt',
'<': 'lt',
'>=': 'gte',
'<=': 'lte',
'~': 'regex'}
REGEX = re.compile(r'^(?P<name>[a-z-A-Z0-9_-]+)'
r'((?P<operator>[!$<>~:=]{1,3})'
r'(?P<value>[^&]+))?$')
def __init__(self, query):
self._conditions = set()
self._parse(query)
def _parse(self, query):
'''
Parse the TQG query and fill the condition set.
:param query: the query to parse
'''
conditions = query.split('&')
for cond in conditions:
m = TqlQuery.REGEX.match(cond)
if not m:
raise TqlParsingError(("Error while parsing, invalid '"
"condition: '%s'") % cond)
# Retrieve each parts:
name = m.group('name')
operator = m.group('operator')
if operator:
value = m.group('value')
else: # Apply the default operator if not specified
operator = ':'
value = '*'
# "not" operator stuff:
if operator.startswith('!') and len(operator) > 1:
operator = operator.lstrip('!')
invert = True
else:
invert = False
# Retrieve the operator callable:
op_name = TqlQuery.OPERATORS.get(operator)
if op_name is None:
raise TqlParsingError("Error while parsing, invalid operator: "
"'%s'" % operator)
op_func = getattr(self, 'op_%s' % op_name, lambda x, y: True)
# Create the condition and add it to the condition set:
cond = TqlCondition(name, value, op_func, invert)
self._conditions.add(cond)
def _match_single(self, obj, tag_name=None, key=lambda o,n: o.get(n)):
'''
Return True if provided object match all the conditions.
If tag_name is provided, the matching will be made only for the
specified tag.
'''
if tag_name is None:
conditions = self._conditions
else:
conditions = [cond for cond in self._conditions
if cond.name == tag_name]
res = (c.operator(key(obj, c.name), c.value) ^ c.invert
for c in conditions)
if res:
return all(res)
else:
return False
def filter(self, objects, tag_name=None, key=lambda o,n: o.get(n)):
'''
Filters objects which don't match with the query.
If tag_name is provided, the matching will be made only for the
specified tag.
:param objects: list of objects to check
:param tag_name: the name of the matching tag
:return: filtered list of objects
'''
return [o for o in objects if self._match_single(o, tag_name, key)]
def has_condition(self, tag_name):
'''
Return True if query has made a condition for the specified tag name.
'''
for cond in self._conditions:
if cond.name == tag_name:
return True
else:
return False
def _get_tags(self):
'''
Get the set of all tags involved in this query.
'''
return set((c.name for c in self._conditions))
tags = property(_get_tags)
def op_glob(self, value, pattern):
if value is None:
return False
return fnmatch(str(value), str(pattern))
def op_lt(self, lvalue, rvalue):
lvalue = multiplicator(lvalue)
rvalue = multiplicator(rvalue)
return lvalue < rvalue
def op_lte(self, lvalue, rvalue):
lvalue = multiplicator(lvalue)
rvalue = multiplicator(rvalue)
return lvalue <= rvalue
def op_gt(self, lvalue, rvalue):
lvalue = multiplicator(lvalue)
rvalue = multiplicator(rvalue)
return lvalue > rvalue
def op_gte(self, lvalue, rvalue):
lvalue = multiplicator(lvalue)
rvalue = multiplicator(rvalue)
return lvalue >= rvalue
def op_regex(self, value, pattern):
if value is None:
return False
try:
return re.match(pattern, value) is not None
except re.error:
raise TqlParsingError('Error in your regex pattern: %s' % pattern)
def op_equal(self, lvalue, rvalue):
if lvalue is None:
return False
if lvalue.isdigit() and rvalue.isdigit(): # Integer comparison:
lvalue = multiplicator(lvalue)
rvalue = multiplicator(rvalue)
return lvalue == rvalue