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
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}"
43
46 vals = {"nothing": 0, "request": 1, "approved": 2}
47
48 @classmethod
50 return [(n, k) for k, n in cls.vals.items() if n != without]
51
54 vals = {"unset": 0,
55 "link": 1,
56 "upload": 2,
57 "pypi": 5,
58 "rubygems": 6,
59 "scm": 8,
60 "custom": 9,
61 }
62
65 """Represents an immutable structure as a json-encoded string.
66
67 Usage::
68
69 JSONEncodedDict(255)
70
71 """
72
73 impl = VARCHAR
74
76 if value is not None:
77 value = json.dumps(value)
78
79 return value
80
82 if value is not None:
83 value = json.loads(value)
84 return value
85
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
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
113 return int(math.ceil(self.total_count / float(self.per_page)))
114
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
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
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
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
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
208
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
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
237
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
305 return map(lambda x: x.name, self.__table__.columns)
306
310 self.host = config.get("REDIS_HOST", "127.0.0.1")
311 self.port = int(config.get("REDIS_PORT", "6379"))
312
314 return StrictRedis(host=self.host, port=self.port)
315
318 """
319 Creates connection to redis, now we use default instance at localhost, no config needed
320 """
321 return StrictRedis()
322
325 if v is None:
326 return False
327 return v.lower() in ("yes", "true", "t", "1")
328
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
351
355
356
357 from sqlalchemy.engine.default import DefaultDialect
358 from sqlalchemy.sql.sqltypes import String, DateTime, NullType
359
360
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)
368 """Teach SA how to literalize various things."""
381 return process
382
393
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
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
427
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
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
462
463 value = int(v[0]) if v[0].isnumeric() else v[0]
464 params[k] = value
465 return params
466
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
525
528 if not url:
529 return None
530
531 return re.sub(r'(\.git)?/*$', '', url)
532
535 if not url:
536 return False
537
538 url = trim_git_url(url)
539 return urlparse(url)
540
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