Package coprs :: Module helpers
[hide private]
[frames] | no frames]

Source Code for Module coprs.helpers

  1  import math 
  2  import random 
  3  import string 
  4   
  5  from six import with_metaclass 
  6  from six.moves.urllib.parse import urlparse, parse_qs 
  7  import re 
  8   
  9  import flask 
 10  import posixpath 
 11  from flask import url_for 
 12  from dateutil import parser as dt_parser 
 13  from netaddr import IPAddress, IPNetwork 
 14  from redis import StrictRedis 
 15  from sqlalchemy.types import TypeDecorator, VARCHAR 
 16  import json 
 17   
 18  from copr_common.enums import EnumType 
 19  from copr_common.rpm import splitFilename 
 20  from coprs import constants 
 21  from coprs import app 
22 23 24 -def generate_api_token(size=30):
25 """ Generate a random string used as token to access the API 26 remotely. 27 28 :kwarg: size, the size of the token to generate, defaults to 30 29 chars. 30 :return: a string, the API token for the user. 31 """ 32 return ''.join(random.choice(string.ascii_lowercase) for x in range(size))
33 34 35 REPO_DL_STAT_FMT = "repo_dl_stat::{copr_user}@{copr_project_name}:{copr_name_release}" 36 CHROOT_REPO_MD_DL_STAT_FMT = "chroot_repo_metadata_dl_stat:hset::{copr_user}@{copr_project_name}:{copr_chroot}" 37 CHROOT_RPMS_DL_STAT_FMT = "chroot_rpms_dl_stat:hset::{copr_user}@{copr_project_name}:{copr_chroot}" 38 PROJECT_RPMS_DL_STAT_FMT = "project_rpms_dl_stat:hset::{copr_user}@{copr_project_name}"
39 40 41 -class CounterStatType(object):
42 REPO_DL = "repo_dl"
43
44 45 -class PermissionEnum(with_metaclass(EnumType, object)):
46 vals = {"nothing": 0, "request": 1, "approved": 2} 47 48 @classmethod
49 - def choices_list(cls, without=-1):
50 return [(n, k) for k, n in cls.vals.items() if n != without]
51
52 53 -class BuildSourceEnum(with_metaclass(EnumType, object)):
54 vals = {"unset": 0, 55 "link": 1, # url 56 "upload": 2, # pkg, tmp, url 57 "pypi": 5, # package_name, version, python_versions 58 "rubygems": 6, # gem_name 59 "scm": 8, # type, clone_url, committish, subdirectory, spec, srpm_build_method 60 "custom": 9, # user-provided script to build sources 61 }
62
63 64 -class JSONEncodedDict(TypeDecorator):
65 """Represents an immutable structure as a json-encoded string. 66 67 Usage:: 68 69 JSONEncodedDict(255) 70 71 """ 72 73 impl = VARCHAR 74
75 - def process_bind_param(self, value, dialect):
76 if value is not None: 77 value = json.dumps(value) 78 79 return value
80
81 - def process_result_value(self, value, dialect):
82 if value is not None: 83 value = json.loads(value) 84 return value
85
86 87 -class Paginator(object):
88 - def __init__(self, query, total_count, page=1, 89 per_page_override=None, urls_count_override=None, 90 additional_params=None):
91 92 self.query = query 93 self.total_count = total_count 94 self.page = page 95 self.per_page = per_page_override or constants.ITEMS_PER_PAGE 96 self.urls_count = urls_count_override or constants.PAGES_URLS_COUNT 97 self.additional_params = additional_params or dict() 98 99 self._sliced_query = None
100
101 - def page_slice(self, page):
102 return (self.per_page * (page - 1), 103 self.per_page * page)
104 105 @property
106 - def sliced_query(self):
107 if not self._sliced_query: 108 self._sliced_query = self.query[slice(*self.page_slice(self.page))] 109 return self._sliced_query
110 111 @property
112 - def pages(self):
113 return int(math.ceil(self.total_count / float(self.per_page)))
114
115 - def border_url(self, request, start):
116 if start: 117 if self.page - 1 > self.urls_count // 2: 118 return self.url_for_other_page(request, 1), 1 119 else: 120 if self.page < self.pages - self.urls_count // 2: 121 return self.url_for_other_page(request, self.pages), self.pages 122 123 return None
124
125 - def get_urls(self, request):
126 left_border = self.page - self.urls_count // 2 127 left_border = 1 if left_border < 1 else left_border 128 right_border = self.page + self.urls_count // 2 129 right_border = self.pages if right_border > self.pages else right_border 130 131 return [(self.url_for_other_page(request, i), i) 132 for i in range(left_border, right_border + 1)]
133
134 - def url_for_other_page(self, request, page):
135 args = request.view_args.copy() 136 args["page"] = page 137 args.update(self.additional_params) 138 return flask.url_for(request.endpoint, **args)
139
140 141 -def chroot_to_branch(chroot):
142 """ 143 Get a git branch name from chroot. Follow the fedora naming standard. 144 """ 145 os, version, arch = chroot.rsplit("-", 2) 146 if os == "fedora": 147 if version == "rawhide": 148 return "master" 149 os = "f" 150 elif os == "epel" and int(version) <= 6: 151 os = "el" 152 elif os == "mageia" and version == "cauldron": 153 os = "cauldron" 154 version = "" 155 elif os == "mageia": 156 os = "mga" 157 return "{}{}".format(os, version)
158
159 160 -def parse_package_name(pkg):
161 """ 162 Parse package name from possibly incomplete nvra string. 163 """ 164 165 if pkg.count(".") >= 3 and pkg.count("-") >= 2: 166 return splitFilename(pkg)[0] 167 168 # doesn"t seem like valid pkg string, try to guess package name 169 result = "" 170 pkg = pkg.replace(".rpm", "").replace(".src", "") 171 172 for delim in ["-", "."]: 173 if delim in pkg: 174 parts = pkg.split(delim) 175 for part in parts: 176 if any(map(lambda x: x.isdigit(), part)): 177 return result[:-1] 178 179 result += part + "-" 180 181 return result[:-1] 182 183 return pkg
184
185 186 -def generate_repo_url(mock_chroot, url):
187 """ Generates url with build results for .repo file. 188 No checks if copr or mock_chroot exists. 189 """ 190 os_version = mock_chroot.os_version 191 192 if mock_chroot.os_release == "fedora": 193 if mock_chroot.os_version != "rawhide": 194 os_version = "$releasever" 195 196 if mock_chroot.os_release == "opensuse-leap": 197 os_version = "$releasever" 198 199 if mock_chroot.os_release == "mageia": 200 if mock_chroot.os_version != "cauldron": 201 os_version = "$releasever" 202 203 url = posixpath.join( 204 url, "{0}-{1}-{2}/".format(mock_chroot.os_release, 205 os_version, "$basearch")) 206 207 return url
208
209 210 -def fix_protocol_for_backend(url):
211 """ 212 Ensure that url either has http or https protocol according to the 213 option in app config "ENFORCE_PROTOCOL_FOR_BACKEND_URL" 214 """ 215 if app.config["ENFORCE_PROTOCOL_FOR_BACKEND_URL"] == "https": 216 return url.replace("http://", "https://") 217 elif app.config["ENFORCE_PROTOCOL_FOR_BACKEND_URL"] == "http": 218 return url.replace("https://", "http://") 219 else: 220 return url
221
222 223 -def fix_protocol_for_frontend(url):
224 """ 225 Ensure that url either has http or https protocol according to the 226 option in app config "ENFORCE_PROTOCOL_FOR_FRONTEND_URL" 227 """ 228 if app.config["ENFORCE_PROTOCOL_FOR_FRONTEND_URL"] == "https": 229 return url.replace("http://", "https://") 230 elif app.config["ENFORCE_PROTOCOL_FOR_FRONTEND_URL"] == "http": 231 return url.replace("https://", "http://") 232 else: 233 return url
234
235 236 -class Serializer(object):
237
238 - def to_dict(self, options=None):
239 """ 240 Usage: 241 242 SQLAlchObject.to_dict() => returns a flat dict of the object 243 SQLAlchObject.to_dict({"foo": {}}) => returns a dict of the object 244 and will include a flat dict of object foo inside of that 245 SQLAlchObject.to_dict({"foo": {"bar": {}}, "spam": {}}) => returns 246 a dict of the object, which will include dict of foo 247 (which will include dict of bar) and dict of spam. 248 249 Options can also contain two special values: __columns_only__ 250 and __columns_except__ 251 252 If present, the first makes only specified fields appear, 253 the second removes specified fields. Both of these fields 254 must be either strings (only works for one field) or lists 255 (for one and more fields). 256 257 SQLAlchObject.to_dict({"foo": {"__columns_except__": ["id"]}, 258 "__columns_only__": "name"}) => 259 260 The SQLAlchObject will only put its "name" into the resulting dict, 261 while "foo" all of its fields except "id". 262 263 Options can also specify whether to include foo_id when displaying 264 related foo object (__included_ids__, defaults to True). 265 This doesn"t apply when __columns_only__ is specified. 266 """ 267 268 result = {} 269 if options is None: 270 options = {} 271 columns = self.serializable_attributes 272 273 if "__columns_only__" in options: 274 columns = options["__columns_only__"] 275 else: 276 columns = set(columns) 277 if "__columns_except__" in options: 278 columns_except = options["__columns_except__"] 279 if not isinstance(options["__columns_except__"], list): 280 columns_except = [options["__columns_except__"]] 281 282 columns -= set(columns_except) 283 284 if ("__included_ids__" in options and 285 options["__included_ids__"] is False): 286 287 related_objs_ids = [ 288 r + "_id" for r, _ in options.items() 289 if not r.startswith("__")] 290 291 columns -= set(related_objs_ids) 292 293 columns = list(columns) 294 295 for column in columns: 296 result[column] = getattr(self, column) 297 298 for related, values in options.items(): 299 if hasattr(self, related): 300 result[related] = getattr(self, related).to_dict(values) 301 return result
302 303 @property
304 - def serializable_attributes(self):
305 return map(lambda x: x.name, self.__table__.columns)
306
307 308 -class RedisConnectionProvider(object):
309 - def __init__(self, config):
310 self.host = config.get("REDIS_HOST", "127.0.0.1") 311 self.port = int(config.get("REDIS_PORT", "6379"))
312
313 - def get_connection(self):
314 return StrictRedis(host=self.host, port=self.port)
315
316 317 -def get_redis_connection():
318 """ 319 Creates connection to redis, now we use default instance at localhost, no config needed 320 """ 321 return StrictRedis()
322
323 324 -def str2bool(v):
325 if v is None: 326 return False 327 return v.lower() in ("yes", "true", "t", "1")
328
329 330 -def copr_url(view, copr, **kwargs):
331 """ 332 Examine given copr and generate proper URL for the `view` 333 334 Values of `username/group_name` and `coprname` are automatically passed as the first two URL parameters, 335 and therefore you should *not* pass them manually. 336 337 Usage: 338 copr_url("coprs_ns.foo", copr) 339 copr_url("coprs_ns.foo", copr, arg1='bar', arg2='baz) 340 """ 341 if copr.is_a_group_project: 342 return url_for(view, group_name=copr.group.name, coprname=copr.name, **kwargs) 343 return url_for(view, username=copr.user.name, coprname=copr.name, **kwargs)
344
345 346 -def url_for_copr_view(view, group_view, copr, **kwargs):
347 if copr.is_a_group_project: 348 return url_for(group_view, group_name=copr.group.name, coprname=copr.name, **kwargs) 349 else: 350 return url_for(view, username=copr.user.name, coprname=copr.name, **kwargs)
351
352 353 -def url_for_copr_builds(copr):
354 return copr_url("coprs_ns.copr_builds", copr)
355 356 357 from sqlalchemy.engine.default import DefaultDialect 358 from sqlalchemy.sql.sqltypes import String, DateTime, NullType 359 360 # python2/3 compatible. 361 PY3 = str is not bytes 362 text = str if PY3 else unicode 363 int_type = int if PY3 else (int, long) 364 str_type = str if PY3 else (str, unicode)
365 366 367 -class StringLiteral(String):
368 """Teach SA how to literalize various things."""
369 - def literal_processor(self, dialect):
370 super_processor = super(StringLiteral, self).literal_processor(dialect) 371 372 def process(value): 373 if isinstance(value, int_type): 374 return text(value) 375 if not isinstance(value, str_type): 376 value = text(value) 377 result = super_processor(value) 378 if isinstance(result, bytes): 379 result = result.decode(dialect.encoding) 380 return result
381 return process
382
383 384 -class LiteralDialect(DefaultDialect):
385 colspecs = { 386 # prevent various encoding explosions 387 String: StringLiteral, 388 # teach SA about how to literalize a datetime 389 DateTime: StringLiteral, 390 # don't format py2 long integers to NULL 391 NullType: StringLiteral, 392 }
393
394 395 -def literal_query(statement):
396 """NOTE: This is entirely insecure. DO NOT execute the resulting strings. 397 This can be used for debuggin - it is not and should not be used in production 398 code. 399 400 It is useful if you want to debug an sqlalchemy query, i.e. copy the 401 resulting SQL query into psql console and try to tweak it so that it 402 actually works or works faster. 403 """ 404 import sqlalchemy.orm 405 if isinstance(statement, sqlalchemy.orm.Query): 406 statement = statement.statement 407 return statement.compile( 408 dialect=LiteralDialect(), 409 compile_kwargs={'literal_binds': True}, 410 ).string
411
412 413 -def stream_template(template_name, **context):
414 app.update_template_context(context) 415 t = app.jinja_env.get_template(template_name) 416 rv = t.stream(context) 417 rv.enable_buffering(2) 418 return rv
419
420 421 -def generate_repo_name(repo_url):
422 """ based on url, generate repo name """ 423 repo_url = re.sub("[^a-zA-Z0-9]", '_', repo_url) 424 repo_url = re.sub("(__*)", '_', repo_url) 425 repo_url = re.sub("(_*$)|^_*", '', repo_url) 426 return repo_url
427
428 429 -def pre_process_repo_url(chroot, repo_url):
430 """ 431 Expands variables and sanitize repo url to be used for mock config 432 """ 433 parsed_url = urlparse(repo_url) 434 if parsed_url.scheme == "copr": 435 user = parsed_url.netloc 436 prj = parsed_url.path.split("/")[1] 437 repo_url = "/".join([ 438 flask.current_app.config["BACKEND_BASE_URL"], 439 "results", user, prj, chroot 440 ]) + "/" 441 442 repo_url = repo_url.replace("$chroot", chroot) 443 repo_url = repo_url.replace("$distname", chroot.rsplit("-", 2)[0]) 444 return repo_url
445
446 447 -def parse_repo_params(repo, supported_keys=None):
448 """ 449 :param repo: str repo from Copr/CoprChroot/Build/... 450 :param supported_keys list of supported optional parameters 451 :return: dict of optional parameters parsed from the repo URL 452 """ 453 supported_keys = supported_keys or ["priority"] 454 if not repo.startswith("copr://"): 455 return {} 456 457 params = {} 458 qs = parse_qs(urlparse(repo).query) 459 for k, v in qs.items(): 460 if k in supported_keys: 461 # parse_qs returns values as lists, but we allow setting the param only once, 462 # so we can take just first value from it 463 value = int(v[0]) if v[0].isnumeric() else v[0] 464 params[k] = value 465 return params
466
467 468 -def generate_build_config(copr, chroot_id):
469 """ Return dict with proper build config contents """ 470 chroot = None 471 for i in copr.copr_chroots: 472 if i.mock_chroot.name == chroot_id: 473 chroot = i 474 if not chroot: 475 return {} 476 477 packages = "" if not chroot.buildroot_pkgs else chroot.buildroot_pkgs 478 479 repos = [{ 480 "id": "copr_base", 481 "baseurl": copr.repo_url + "/{}/".format(chroot_id), 482 "name": "Copr repository", 483 }] 484 485 if not copr.auto_createrepo: 486 repos.append({ 487 "id": "copr_base_devel", 488 "baseurl": copr.repo_url + "/{}/devel/".format(chroot_id), 489 "name": "Copr buildroot", 490 }) 491 492 def get_additional_repo_views(repos_list): 493 repos = [] 494 for repo in repos_list: 495 params = parse_repo_params(repo) 496 repo_view = { 497 "id": generate_repo_name(repo), 498 "baseurl": pre_process_repo_url(chroot_id, repo), 499 "name": "Additional repo " + generate_repo_name(repo), 500 } 501 repo_view.update(params) 502 repos.append(repo_view) 503 return repos
504 505 repos.extend(get_additional_repo_views(copr.repos_list)) 506 repos.extend(get_additional_repo_views(chroot.repos_list)) 507 508 return { 509 'project_id': copr.repo_id, 510 'additional_packages': packages.split(), 511 'repos': repos, 512 'chroot': chroot_id, 513 'use_bootstrap_container': copr.use_bootstrap_container, 514 'with_opts': chroot.with_opts.split(), 515 'without_opts': chroot.without_opts.split(), 516 } 517
518 519 -def generate_additional_repos(copr_chroot):
520 base_repo = "copr://{}".format(copr_chroot.copr.full_name) 521 repos = [base_repo] + copr_chroot.repos_list + copr_chroot.copr.repos_list 522 if not copr_chroot.copr.auto_createrepo: 523 repos.append("copr://{}/devel".format(copr_chroot.copr.full_name)) 524 return repos
525
526 527 -def trim_git_url(url):
528 if not url: 529 return None 530 531 return re.sub(r'(\.git)?/*$', '', url)
532
533 534 -def get_parsed_git_url(url):
535 if not url: 536 return False 537 538 url = trim_git_url(url) 539 return urlparse(url)
540
541 542 -def get_copr_repo_id(copr_dir):
543 """ 544 We cannot really switch to the new 545 copr:{hostname}:{owner}:{project} format yet, because it is implemented in 546 dnf-plugins-core-3.x which is only on F29+ 547 548 Since the F29+ plugin is able to work with both old and new formats, we can 549 safely stay with the old one until F28 is still supported. Once it goes EOL, 550 we can migrate to the new format. 551 552 New format is: 553 554 return "copr:{0}:{1}:{2}".format(app.config["PUBLIC_COPR_HOSTNAME"].split(":")[0], 555 copr_dir.copr.owner_name.replace("@", "group_"), 556 copr_dir.name) 557 558 """ 559 return copr_dir.repo_id
560