/usr/lib/python2.7/dist-packages/koji/policy.py is in koji-common 1.10.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | # Copyright (c) 2008-2014 Red Hat, Inc.
#
# Koji is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation;
# version 2.1 of the License.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this software; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors:
# Mike McLean <mikem@redhat.com>
import fnmatch
import koji
class BaseSimpleTest(object):
"""Abstract base class for simple tests"""
#Provide the name of the test
name = None
def __init__(self, str):
"""Read the test parameters from string"""
self.str = str
def run(self, data):
"""Run the test against data provided"""
raise NotImplementedError
def __str__(self):
return self.str
# The following tests are generic enough that we can place them here
class TrueTest(BaseSimpleTest):
name = 'true'
def run(self, data):
return True
class FalseTest(BaseSimpleTest):
name = 'false'
def run(self, data):
return False
class AllTest(TrueTest):
name = 'all'
#alias for true
class NoneTest(FalseTest):
name = 'none'
#alias for false
class HasTest(BaseSimpleTest):
"""Test if policy data contains a field"""
name = "has"
def __init__(self, str):
try:
self.field = str.split()[1]
except IndexError:
raise koji.GenericError, "Invalid or missing field in policy test"
def run(self, data):
return self.field in data
class BoolTest(BaseSimpleTest):
"""Test a field in the data as a boolean value
This test can be used as-is, or it can be subclassed to
test a specific field
Syntax:
name [field]
"""
name = 'bool'
field = None
def run(self, data):
args = self.str.split()[1:]
if self.field is None:
field = args[0]
else:
# expected when we are subclassed
field = self.field
return bool(data[field])
class MatchTest(BaseSimpleTest):
"""Matches a field in the data against glob patterns
True if any of the expressions match, else False
This test can be used as-is, or it can be subclassed to
test a specific field
Syntax:
name [field] pattern1 [pattern2 ...]
"""
name = 'match'
field = None
def run(self, data):
args = self.str.split()[1:]
if self.field is None:
field = args[0]
args = args[1:]
else:
# expected when we are subclassed
field = self.field
for pattern in args:
if fnmatch.fnmatch(data[field], pattern):
return True
return False
class CompareTest(BaseSimpleTest):
"""Simple numeric field comparison
Supports basic numeric comparisons. The right operand must be a valid number
This test can be used as-is, or it can be subclassed to
test a specific field
Syntax:
name [field] OP number
"""
name = 'compare'
field = None
allow_float = True
operators = {
'<' : lambda a, b: a < b,
'>' : lambda a, b: a > b,
'<=' : lambda a, b: a <= b,
'>=' : lambda a, b: a >= b,
'=' : lambda a, b: a == b,
'!=' : lambda a, b: a != b,
}
def __init__(self, str):
"""Read the test parameters from string"""
super(CompareTest, self).__init__(str)
if self.field is None:
# field OP number
self.field, cmp, value = str.split(None, 3)[1:]
else:
# OP number
cmp, value = str.split(None, 2)[1:]
self.func = self.operators.get(cmp, None)
if self.func is None:
raise koji.GenericError, "Invalid comparison in test."
try:
self.value = int(value)
except ValueError:
if not self.allow_float:
raise
self.value = float(value)
def run(self, data):
return self.func(data[self.field], self.value)
class SimpleRuleSet(object):
def __init__(self, rules, tests):
self.tests = tests
self.rules = self.parse_rules(rules)
self.lastrule = None
self.lastaction = None
def parse_rules(self, lines):
"""Parse rules into a ruleset data structure
At the top level, the structure is a set of rules
[rule1, rule2, ...]
Each rule is a pair
[tests, negate, action ]
Tests is a list of test handlers:
[handler1, handler2, ...]
Action can either be a string or a chained ruleset
"action"
or
[subrule1, subrule2, ...]
Putting it all together, you get something like this:
[[[test1, test2], negate, "action"],
[[test], negate,
[[[test1, test2], negate, "action"],
[[test1, test2, test3], negate
[[[test1, test2], negate, "action"]]]]]]
"""
cursor = []
self.ruleset = cursor
stack = []
for line in lines:
rule = self.parse_line(line)
if rule is None:
#blank/etc
continue
tests, negate, action = rule
if action == '{':
#nested rules
child = []
cursor.append([tests, negate, child])
stack.append(cursor)
cursor = child
elif action == '}':
if not stack:
raise koji.GenericError, "nesting error in rule set"
cursor = stack.pop()
else:
cursor.append(rule)
if stack:
# unclosed {
raise koji.GenericError, "nesting error in rule set"
def parse_line(self, line):
"""Parse line as a rule
Expected format is:
test [params] [&& test [params] ...] :: action-if-true
test [params] [&& test [params] ...] !! action-if-false
(syntax is !! instead of ||, because otherwise folks might think
they can mix && and ||, which is /not/ supported)
For complex rules:
test [params [&& ...]] :: {
test [params [&& ...]] :: action
test [params [&& ...]] :: {
...
}
}
Each closing brace must be on a line by itself
"""
line = line.split('#', 1)[0].strip()
if not line:
#blank or all comment
return None
if line == '}':
return None, False, '}'
#?? allow }} ??
negate = False
pos = line.rfind('::')
if pos == -1:
pos = line.rfind('!!')
if pos == -1:
raise Exception, "bad policy line: %s" % line
negate = True
tests = line[:pos]
action = line[pos+2:]
tests = [self.get_test_handler(x) for x in tests.split('&&')]
action = action.strip()
# just return action = { for nested rules
return tests, negate, action
def get_test_handler(self, str):
name = str.split(None,1)[0]
try:
return self.tests[name](str)
except KeyError:
raise koji.GenericError, "missing test handler: %s" % name
def all_actions(self):
"""report a list of all actions in the ruleset
(only the first word of the action is considered)
"""
def _recurse(rules, index):
for tests, negate, action in rules:
if isinstance(action, list):
_recurse(action, index)
else:
name = action.split(None,1)[0]
index[name] = 1
index = {}
_recurse(self.ruleset, index)
return index.keys()
def _apply(self, rules, data, top=False):
for tests, negate, action in rules:
if top:
self.lastrule = []
value = False
for test in tests:
if not test.run(data):
break
else:
#all tests in current rule passed
value = True
if negate:
value = not value
if value:
self.lastrule.append([tests, negate])
if isinstance(action, list):
# action is a list of subrules
ret = self._apply(action, data)
if ret is not None:
return ret
# if ret is None, then none of the subrules matched,
# so we keep going
else:
return action
return None
def apply(self, data):
self.lastrule = []
self.lastaction = self._apply(self.ruleset, data, top=True)
return self.lastaction
def last_rule(self):
if self.lastrule is None:
return None
ret = []
for (tests, negate) in self.lastrule:
line = '&&'.join([str(t) for t in tests])
if negate:
line += ' !! '
else:
line += ' :: '
ret.append(line)
ret = '... '.join(ret)
if self.lastaction is None:
ret += "(no match)"
else:
ret += self.lastaction
return ret
def findSimpleTests(namespace):
"""Search namespace for subclasses of BaseSimpleTest
This is a convenience function for initializing a SimpleRuleSet instance
namespace can be a dict (e.g. globals()), or a list of dicts
returns a dictionary of the found subclasses, indexed by name
"""
if not isinstance(namespace, (list, tuple)):
namespace = (namespace,)
ret = {}
for ns in namespace:
for key, value in ns.iteritems():
if value is BaseSimpleTest:
# skip this abstract base class if we encounter it
# this module contains generic tests, so it is valid to include it
# in the namespace list
continue
if type(value) == type(BaseSimpleTest) and issubclass(value, BaseSimpleTest):
name = getattr(value, 'name', None)
if not name:
#use the class name
name = key
#but trim 'Test' from the end
if name.endswith('Test') and len(name) > 4:
name = name[:-4]
ret.setdefault(name, value)
#...so first test wins in case of name overlap
return ret
|