/usr/share/koji-web/lib/kojiweb/util.py is in koji-servers 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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | # utility functions for koji web interface
#
# Copyright (c) 2005-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 Bonnet <mikeb@redhat.com>
# Mike McLean <mikem@redhat.com>
import Cheetah.Template
import datetime
import koji
from koji.util import md5_constructor
import os
import stat
import time
#a bunch of exception classes that explainError needs
from socket import error as socket_error
from socket import sslerror as socket_sslerror
from xmlrpclib import ProtocolError
from xml.parsers.expat import ExpatError
class NoSuchException(Exception):
pass
try:
# pyOpenSSL might not be around
from OpenSSL.SSL import Error as SSL_Error
except:
SSL_Error = NoSuchException
themeInfo = {}
themeCache = {}
def _initValues(environ, title='Build System Info', pageID='summary'):
global themeInfo
global themeCache
values = {}
values['siteName'] = environ['koji.options'].get('SiteName', 'Koji')
values['title'] = title
values['pageID'] = pageID
values['currentDate'] = str(datetime.datetime.now())
values['literalFooter'] = environ['koji.options'].get('LiteralFooter', True)
themeCache.clear()
themeInfo.clear()
themeInfo['name'] = environ['koji.options'].get('KojiTheme', None)
themeInfo['staticdir'] = environ['koji.options'].get('KojiStaticDir', '/usr/share/koji-web/static')
environ['koji.values'] = values
return values
def themePath(path, local=False):
global themeInfo
global themeCache
local = bool(local)
if (path, local) in themeCache:
return themeCache[path, local]
if not themeInfo['name']:
if local:
ret = os.path.join(themeInfo['staticdir'], path)
else:
ret = "/koji-static/%s" % path
else:
themepath = os.path.join(themeInfo['staticdir'], 'themes', themeInfo['name'], path)
if os.path.exists(themepath):
if local:
ret = themepath
else:
ret = "/koji-static/themes/%s/%s" % (themeInfo['name'], path)
else:
if local:
ret = os.path.join(themeInfo['staticdir'], path)
else:
ret = "/koji-static/%s" % path
themeCache[path, local] = ret
return ret
class DecodeUTF8(Cheetah.Filters.Filter):
def filter(self, *args, **kw):
"""Convert all strs to unicode objects"""
result = super(DecodeUTF8, self).filter(*args, **kw)
if isinstance(result, unicode):
pass
else:
result = result.decode('utf-8', 'replace')
return result
# Escape ampersands so the output can be valid XHTML
class XHTMLFilter(DecodeUTF8):
def filter(self, *args, **kw):
result = super(XHTMLFilter, self).filter(*args, **kw)
result = result.replace('&', '&')
result = result.replace('&amp;', '&')
result = result.replace('&nbsp;', ' ')
result = result.replace('&lt;', '<')
result = result.replace('&gt;', '>')
return result
TEMPLATES = {}
def _genHTML(environ, fileName):
reqdir = os.path.dirname(environ['SCRIPT_FILENAME'])
if os.getcwd() != reqdir:
os.chdir(reqdir)
if 'koji.currentUser' in environ:
environ['koji.values']['currentUser'] = environ['koji.currentUser']
else:
environ['koji.values']['currentUser'] = None
environ['koji.values']['authToken'] = _genToken(environ)
if not environ['koji.values'].has_key('mavenEnabled'):
if 'koji.session' in environ:
environ['koji.values']['mavenEnabled'] = environ['koji.session'].mavenEnabled()
else:
environ['koji.values']['mavenEnabled'] = False
if not environ['koji.values'].has_key('winEnabled'):
if 'koji.session' in environ:
environ['koji.values']['winEnabled'] = environ['koji.session'].winEnabled()
else:
environ['koji.values']['winEnabled'] = False
tmpl_class = TEMPLATES.get(fileName)
if not tmpl_class:
tmpl_class = Cheetah.Template.Template.compile(file=fileName)
TEMPLATES[fileName] = tmpl_class
tmpl_inst = tmpl_class(namespaces=[environ['koji.values']], filter=XHTMLFilter)
return tmpl_inst.respond().encode('utf-8', 'replace')
def _truncTime():
now = datetime.datetime.now()
# truncate to the nearest 15 minutes
return now.replace(minute=(now.minute / 15 * 15), second=0, microsecond=0)
def _genToken(environ, tstamp=None):
if 'koji.currentLogin' in environ and environ['koji.currentLogin']:
user = environ['koji.currentLogin']
else:
return ''
if tstamp == None:
tstamp = _truncTime()
return md5_constructor(user + str(tstamp) + environ['koji.options']['Secret'].value).hexdigest()[-8:]
def _getValidTokens(environ):
tokens = []
now = _truncTime()
for delta in (0, 15, 30):
token_time = now - datetime.timedelta(minutes=delta)
token = _genToken(environ, token_time)
if token:
tokens.append(token)
return tokens
def toggleOrder(template, sortKey, orderVar='order'):
"""
If orderVar equals 'sortKey', return '-sortKey', else
return 'sortKey'.
"""
if template.getVar(orderVar) == sortKey:
return '-' + sortKey
else:
return sortKey
def toggleSelected(template, var, option):
"""
If the passed in variable var equals the literal value in option,
return 'selected="selected"', otherwise return ''.
Used for setting the selected option in select boxes.
"""
if var == option:
return 'selected="selected"'
else:
return ''
def sortImage(template, sortKey, orderVar='order'):
"""
Return an html img tag suitable for inclusion in the sortKey of a sortable table,
if the sortValue is "sortKey" or "-sortKey".
"""
orderVal = template.getVar(orderVar)
if orderVal == sortKey:
return '<img src="%s" class="sort" alt="ascending sort"/>' % themePath("images/gray-triangle-up.gif")
elif orderVal == '-' + sortKey:
return '<img src="%s" class="sort" alt="descending sort"/>' % themePath("images/gray-triangle-down.gif")
else:
return ''
def passthrough(template, *vars):
"""
Construct a string suitable for use as URL
parameters. For each variable name in *vars,
if the template has a corresponding non-None value,
append that name-value pair to the string. The name-value
pairs will be separated by ampersands (&), and prefixed by
an ampersand if there are any name-value pairs. If there
are no name-value pairs, an empty string will be returned.
"""
result = []
for var in vars:
value = template.getVar(var, default=None)
if value != None:
result.append('%s=%s' % (var, value))
if result:
return '&' + '&'.join(result)
else:
return ''
def passthrough_except(template, *exclude):
"""
Construct a string suitable for use as URL
parameters. The template calling this method must have
previously used
#attr _PASSTHROUGH = ...
to define the list of variable names to be passed-through.
Any variables names passed in will be excluded from the
list of variables in the output string.
"""
passvars = []
for var in template._PASSTHROUGH:
if not var in exclude:
passvars.append(var)
return passthrough(template, *passvars)
def sortByKeyFunc(key, noneGreatest=False):
"""Return a function to sort a list of maps by the given key.
If the key starts with '-', sort in reverse order. If noneGreatest
is True, None will sort higher than all other values (instead of lower).
"""
if noneGreatest:
# Normally None evaluates to be less than every other value
# Invert the comparison so it always evaluates to greater
cmpFunc = lambda a, b: (a is None or b is None) and -(cmp(a, b)) or cmp(a, b)
else:
cmpFunc = cmp
if key.startswith('-'):
key = key[1:]
sortFunc = lambda a, b: cmpFunc(b[key], a[key])
else:
sortFunc = lambda a, b: cmpFunc(a[key], b[key])
return sortFunc
def paginateList(values, data, start, dataName, prefix=None, order=None, noneGreatest=False, pageSize=50):
"""
Slice the 'data' list into one page worth. Start at offset
'start' and limit the total number of pages to pageSize
(defaults to 50). 'dataName' is the name under which the
list will be added to the value map, and prefix is the name
under which a number of list-related metadata variables will
be added to the value map.
"""
if order != None:
data.sort(sortByKeyFunc(order, noneGreatest))
totalRows = len(data)
if start:
start = int(start)
if not start or start < 0:
start = 0
data = data[start:(start + pageSize)]
count = len(data)
_populateValues(values, dataName, prefix, data, totalRows, start, count, pageSize, order)
return data
def paginateMethod(server, values, methodName, args=None, kw=None,
start=None, dataName=None, prefix=None, order=None, pageSize=50):
"""Paginate the results of the method with the given name when called with the given args and kws.
The method must support the queryOpts keyword parameter, and pagination is done in the database."""
if args is None:
args = []
if kw is None:
kw = {}
if start:
start = int(start)
if not start or start < 0:
start = 0
if not dataName:
raise StandardError, 'dataName must be specified'
kw['queryOpts'] = {'countOnly': True}
totalRows = getattr(server, methodName)(*args, **kw)
kw['queryOpts'] = {'order': order,
'offset': start,
'limit': pageSize}
data = getattr(server, methodName)(*args, **kw)
count = len(data)
_populateValues(values, dataName, prefix, data, totalRows, start, count, pageSize, order)
return data
def paginateResults(server, values, methodName, args=None, kw=None,
start=None, dataName=None, prefix=None, order=None, pageSize=50):
"""Paginate the results of the method with the given name when called with the given args and kws.
This method should only be used when then method does not support the queryOpts command (because
the logic used to generate the result list prevents filtering/ordering from being done in the database).
The method must return a list of maps."""
if args is None:
args = []
if kw is None:
kw = {}
if start:
start = int(start)
if not start or start < 0:
start = 0
if not dataName:
raise StandardError, 'dataName must be specified'
totalRows = server.count(methodName, *args, **kw)
kw['filterOpts'] = {'order': order,
'offset': start,
'limit': pageSize}
data = server.filterResults(methodName, *args, **kw)
count = len(data)
_populateValues(values, dataName, prefix, data, totalRows, start, count, pageSize, order)
return data
def _populateValues(values, dataName, prefix, data, totalRows, start, count, pageSize, order):
"""Populate the values list with the data about the list provided."""
values[dataName] = data
# Don't use capitalize() to title() here, they mess up
# mixed-case name
values['total' + dataName[0].upper() + dataName[1:]] = totalRows
# Possibly prepend a prefix to the numeric parameters, to avoid namespace collisions
# when there is more than one list on the same page
values[(prefix and prefix + 'Start' or 'start')] = start
values[(prefix and prefix + 'Count' or 'count')] = count
values[(prefix and prefix + 'Range' or 'range')] = pageSize
values[(prefix and prefix + 'Order' or 'order')] = order
currentPage = start / pageSize
values[(prefix and prefix + 'CurrentPage' or 'currentPage')] = currentPage
totalPages = totalRows / pageSize
if totalRows % pageSize > 0:
totalPages += 1
pages = [page for page in range(0, totalPages) if (abs(page - currentPage) < 100 or ((page + 1) % 100 == 0))]
values[(prefix and prefix + 'Pages') or 'pages'] = pages
def stateName(stateID):
"""Convert a numeric build state into a readable name."""
return koji.BUILD_STATES[stateID].lower()
def imageTag(name):
"""Return an img tag that loads an icon with the given name"""
return '<img class="stateimg" src="%s" title="%s" alt="%s"/>' \
% (themePath("images/%s.png" % name), name, name)
def stateImage(stateID):
"""Return an IMG tag that loads an icon appropriate for
the given state"""
name = stateName(stateID)
return imageTag(name)
def brStateName(stateID):
"""Convert a numeric buildroot state into a readable name."""
return koji.BR_STATES[stateID].lower()
def repoStateName(stateID):
"""Convert a numeric repository state into a readable name."""
if stateID == koji.REPO_INIT:
return 'initializing'
elif stateID == koji.REPO_READY:
return 'ready'
elif stateID == koji.REPO_EXPIRED:
return 'expired'
elif stateID == koji.REPO_DELETED:
return 'deleted'
else:
return 'unknown'
def taskState(stateID):
"""Convert a numeric task state into a readable name"""
return koji.TASK_STATES[stateID].lower()
formatTime = koji.formatTime
formatTimeRSS = koji.formatTimeLong
formatTimeLong = koji.formatTimeLong
def formatDep(name, version, flags):
"""Format dependency information into
a human-readable format. Copied from
rpmUtils/miscutils.py:formatRequires()"""
s = name
if flags:
if flags & (koji.RPMSENSE_LESS | koji.RPMSENSE_GREATER |
koji.RPMSENSE_EQUAL):
s = s + " "
if flags & koji.RPMSENSE_LESS:
s = s + "<"
if flags & koji.RPMSENSE_GREATER:
s = s + ">"
if flags & koji.RPMSENSE_EQUAL:
s = s + "="
if version:
s = "%s %s" %(s, version)
return s
def formatMode(mode):
"""Format a numeric mode into a ls-like string describing the access mode."""
if stat.S_ISREG(mode):
result = '-'
elif stat.S_ISDIR(mode):
result = 'd'
elif stat.S_ISCHR(mode):
result = 'c'
elif stat.S_ISBLK(mode):
result = 'b'
elif stat.S_ISFIFO(mode):
result = 'p'
elif stat.S_ISLNK(mode):
result = 'l'
elif stat.S_ISSOCK(mode):
result = 's'
else:
# What is it? Show it like a regular file.
result = '-'
for x in ('USR', 'GRP', 'OTH'):
for y in ('R', 'W', 'X'):
if mode & getattr(stat, 'S_I' + y + x):
result += y.lower()
else:
result += '-'
return result
def rowToggle(template):
"""If the value of template._rowNum is even, return 'row-even';
if it is odd, return 'row-odd'. Increment the value before checking it.
If the template does not have that value, set it to 0."""
if not hasattr(template, '_rowNum'):
template._rowNum = 0
template._rowNum += 1
if template._rowNum % 2:
return 'row-odd'
else:
return 'row-even'
def taskScratchClass(task_object):
""" Return a css class indicating whether or not this task is a scratch
build.
"""
request = task_object['request']
if len(request) >= 3:
opts = request[2]
if opts.get('scratch'):
return "scratch"
return ""
_fileFlags = {1: 'configuration',
2: 'documentation',
4: 'icon',
8: 'missing ok',
16: "don't replace",
64: 'ghost',
128: 'license',
256: 'readme',
512: 'exclude',
1024: 'unpatched',
2048: 'public key'}
def formatFileFlags(flags):
"""Format rpm fileflags for display. Returns
a list of human-readable strings specifying the
flags set in "flags"."""
results = []
for flag, desc in _fileFlags.items():
if flags & flag:
results.append(desc)
return results
def escapeHTML(value):
"""Replace special characters to the text can be displayed in
an HTML page correctly.
< : <
> : >
& : &
"""
if not value:
return value
value = koji.fixEncoding(value)
return value.replace('&', '&').\
replace('<', '<').\
replace('>', '>')
def authToken(template, first=False, form=False):
"""Return the current authToken if it exists.
If form is True, return it enclosed in a hidden input field.
Otherwise, return it in a format suitable for appending to a URL.
If first is True, prefix it with ?, otherwise prefix it
with &. If no authToken exists, return an empty string."""
token = template.getVar('authToken', default=None)
if token != None:
if form:
return '<input type="hidden" name="a" value="%s"/>' % token
if first:
return '?a=' + token
else:
return '&a=' + token
else:
return ''
def explainError(error):
"""Explain an exception in user-consumable terms
Some of the explanations are web-centric, which is why this call is not part
of the main koji library, at least for now...
Returns a tuple: (str, level)
str = explanation in plain text
level = an integer indicating how much traceback data should
be shown:
0 - no traceback data
1 - just the exception
2 - full traceback
"""
str = "An exception has occurred"
level = 2
if isinstance(error, koji.ServerOffline):
str = "The server is offline. Please try again later."
level = 0
elif isinstance(error, koji.ActionNotAllowed):
str = """\
The web interface has tried to do something that your account is not \
allowed to do. This is most likely a bug in the web interface."""
elif isinstance(error, koji.FunctionDeprecated):
str = """\
The web interface has tried to access a deprecated function. This is \
most likely a bug in the web interface."""
elif isinstance(error, koji.RetryError):
str = """\
The web interface is having difficulty communicating with the main \
server and was unable to retry an operation. Most likely this indicates \
a network issue, but it could also be a configuration issue."""
level = 1
elif isinstance(error, koji.GenericError):
if getattr(error, 'fromFault', False):
str = """\
An error has occurred on the main server. This could be a software \
bug, a server configuration issue, or possibly something else."""
else:
str = """\
An error has occurred in the web interface code. This could be due to \
a bug or a configuration issue."""
elif isinstance(error, (socket_error, socket_sslerror)):
str = """\
The web interface is having difficulty communicating with the main \
server. This most likely indicates a network issue."""
level = 1
elif isinstance(error, (ProtocolError, ExpatError)):
str = """\
The main server returned an invalid response. This could be caused by \
a network issue or load issues on the server."""
level = 1
else:
str = "An error has occurred while processing your request."
return str, level
|