Skip to content

Apache DataFusion SQL Query Engine

ARROW-1581: [Packaging] Tooling to make nightly wheels available for install

Krisztián Szűcs3ecc2d4a9019
diff --git a/dev/tasks/crossbow.py b/dev/tasks/crossbow.py
index e46d5026fb..2784062d62 100755
--- a/dev/tasks/crossbow.py
+++ b/dev/tasks/crossbow.py
@@ -23,10 +23,11 @@ import glob
import time
import mimetypes
import textwrap
+import concurrent.futures
from io import StringIO
from pathlib import Path
from textwrap import dedent
-from datetime import datetime
+from datetime import datetime, date
from functools import partial
from collections import namedtuple
@@ -65,6 +66,7 @@ def md(template, *args, **kwargs):
def unflatten(mapping):
+ """Converts a flat tuple => object mapping to hierarchical one"""
result = {}
for path, value in mapping.items():
parents, leaf = path[:-1], path[-1]
@@ -79,6 +81,30 @@ def unflatten(mapping):
return result
+def unflatten_tree(files):
+ """Converts a flat path => object mapping to a hierarchical directories
+
+ Input:
+ {
+ 'path/to/file.a': a_content,
+ 'path/to/file.b': b_content,
+ 'path/file.c': c_content
+ }
+ Output:
+ {
+ 'path': {
+ 'to': {
+ 'file.a': a_content,
+ 'file.b': b_content
+ },
+ 'file.c': c_content
+ }
+ }
+ """
+ files = toolz.keymap(lambda path: tuple(path.split('/')), files)
+ return unflatten(files)
+
+
# configurations for setting up branch skipping
# - appveyor has a feature to skip builds without an appveyor.yml
# - travis reads from the master branch and applies the rules
@@ -294,10 +320,12 @@ class Repo:
refspec = '+refs/heads/*:refs/remotes/origin/*'
self.origin.fetch([refspec])
- def push(self):
- callbacks = GitRemoteCallbacks(self.github_token)
+ def push(self, refs=None, github_token=None):
+ github_token = github_token or self.github_token
+ callbacks = GitRemoteCallbacks(github_token)
+ refs = refs or []
try:
- self.origin.push(self._updated_refs, callbacks=callbacks)
+ self.origin.push(refs + self._updated_refs, callbacks=callbacks)
except pygit2.GitError:
raise RuntimeError('Failed to push updated references, '
'potentially because of credential issues: {}'
@@ -373,21 +401,22 @@ class Repo:
tree_id = builder.write()
return tree_id
- def create_branch(self, branch_name, files, parents=[], message='',
- signature=None):
- # 1. create tree
- files = toolz.keymap(lambda path: tuple(path.split('/')), files)
- files = unflatten(files)
+ def create_commit(self, files, parents=None, message='',
+ reference_name=None):
+ parents = parents or []
tree_id = self.create_tree(files)
- # 2. create commit with the tree created above
- # TODO(kszucs): pass signature explicitly
author = committer = self.signature
- commit_id = self.repo.create_commit(None, author, committer, message,
- tree_id, parents)
- commit = self.repo[commit_id]
+ commit_id = self.repo.create_commit(reference_name, author, committer,
+ message, tree_id, parents)
+ return self.repo[commit_id]
- # 3. create branch pointing to the previously created commit
+ def create_branch(self, branch_name, files, parents=None, message='',
+ signature=None):
+ # create commit with the passed tree
+ commit = self.create_commit(files, parents=parents, message=message)
+
+ # create branch pointing to the previously created commit
branch = self.repo.create_branch(branch_name, commit)
# append to the pushable references
@@ -420,12 +449,13 @@ class Repo:
user, repo = m.group(1), m.group(2)
return user, repo
- def as_github_repo(self):
+ def as_github_repo(self, github_token=None):
"""Converts it to a repository object which wraps the GitHub API"""
if self._github_repo is None:
+ github_token = github_token or self.github_token
username, reponame = self._parse_github_user_repo()
- gh = github3.login(token=self.github_token)
- return gh.repository(username, reponame)
+ gh = github3.login(token=github_token)
+ self._github_repo = gh.repository(username, reponame)
return self._github_repo
def github_commit_status(self, commit):
@@ -559,10 +589,34 @@ class Queue(Repo):
job_name = '{}-{}'.format(prefix, latest_id)
return self.get(job_name)
+ def date_of(self, job):
+ # it'd be better to bound to the queue repository on deserialization
+ # and reorganize these methods to Job
+ branch_name = 'origin/{}'.format(job.branch)
+ branch = self.repo.branches[branch_name]
+ commit = self.repo[branch.target]
+ return date.fromtimestamp(commit.commit_time)
+
+ def jobs(self, pattern):
+ """Return jobs sorted by its identifier in reverse order"""
+ job_names = []
+ for name in self.repo.branches.remote:
+ origin, name = name.split('/', 1)
+ result = re.match(pattern, name)
+ if result:
+ job_names.append(name)
+
+ for name in sorted(job_names, reverse=True):
+ yield self.get(name)
+
def get(self, job_name):
branch_name = 'origin/{}'.format(job_name)
branch = self.repo.branches[branch_name]
- content = self.file_contents(branch.target, 'job.yml')
+ try:
+ content = self.file_contents(branch.target, 'job.yml')
+ except KeyError:
+ raise ValueError('No job is found with name: {}'.format(job_name))
+
buffer = StringIO(content.decode('utf-8'))
job = yaml.load(buffer)
job.queue = self
@@ -695,7 +749,8 @@ class Task(Serializable):
params = toolz.merge(self.params, extra_params)
template = Template(path.read_text(), undefined=StrictUndefined)
rendered = template.render(task=self, **params)
- return toolz.merge(_default_tree, {self.filename: rendered})
+ tree = toolz.merge(_default_tree, {self.filename: rendered})
+ return unflatten_tree(tree)
@property
def tag(self):
@@ -762,7 +817,8 @@ class Job(Serializable):
with StringIO() as buf:
yaml.dump(self, buf)
content = buf.getvalue()
- return toolz.merge(_default_tree, {'job.yml': content})
+ tree = toolz.merge(_default_tree, {'job.yml': content})
+ return unflatten_tree(tree)
@property
def queue(self):
@@ -780,6 +836,10 @@ class Job(Serializable):
def email(self):
return os.environ.get('CROSSBOW_EMAIL', self.target.email)
+ @property
+ def date(self):
+ return self.queue.date_of(self)
+
@classmethod
def from_config(cls, config, target, task_whitelist=None,
group_whitelist=None):
@@ -844,6 +904,27 @@ class Job(Serializable):
.format(poll_interval_minutes))
time.sleep(poll_interval_minutes * 60)
+ def query_assets(self, max_workers=4, ignore_prefix=None):
+ # cache the futures for later use
+ if not hasattr(self, '_assets'):
+ self._assets = []
+ with concurrent.futures.ThreadPoolExecutor(max_workers) as pool:
+ for task_name, task in sorted(self.tasks.items()):
+ # HACK: spare some queries because of the rate limit, and
+ # don't query tasks with specified prefix, e.g. "test-"
+ if (ignore_prefix is not None and
+ task_name.startswith(ignore_prefix)):
+ continue
+ self._assets.append((
+ task_name,
+ task,
+ pool.submit(task.status),
+ pool.submit(task.assets)
+ ))
+
+ for task_name, task, status, assets in self._assets:
+ yield (task_name, task, status.result(), assets.result())
+
class Report:
@@ -915,10 +996,7 @@ class ConsoleReport(Report):
echo(self.header())
# write table's body
- for task_name, task in sorted(self.job.tasks.items()):
- status = task.status()
- assets = task.assets()
-
+ for task_name, task, status, assets in self.job.query_assets():
# write summary of the uploaded vs total assets
n_expected = len(assets)
n_uploaded = len(list(filter(None, assets.values())))
@@ -1032,6 +1110,101 @@ class EmailReport(Report):
server.close()
+class GithubPage:
+
+ def __init__(self, jobs):
+ self.jobs = list(jobs)
+
+ def _generate_page(self, links):
+ links = ['<li><a href="{}">{}</a></li>'.format(url, name)
+ for name, url in sorted(links.items())]
+ return '<html><body><ul>{}</ul></body></html>'.format(''.join(links))
+
+ def _generate_toc(self, files):
+ result, links = {}, {}
+ for k, v in files.items():
+ if isinstance(v, dict):
+ result[k] = self._generate_toc(v)
+ links[k] = '{}/'.format(k)
+ else:
+ result[k] = v
+
+ if links:
+ result['index.html'] = self._generate_page(links)
+
+ return result
+
+ def _is_failed(self, status, task_name):
+ # for showing task statuses during the rendering procedure
+ if status.state == 'success':
+ msg = click.style('[ OK] {}'.format(task_name), fg='green')
+ failed = False
+ click.echo(msg)
+ else:
+ msg = click.style('[FAIL] {}'.format(task_name), fg='yellow')
+ failed = True
+
+ click.echo(msg)
+ return failed
+
+ def render_nightlies(self):
+ click.echo('\n\nRENDERING NIGHTLIES')
+ files = {}
+ for job in self.jobs:
+ click.echo('\nJOB: {}'.format(job.branch))
+ tasks = {}
+
+ it = job.query_assets(ignore_prefix='test')
+ for task_name, task, status, assets in it:
+ links = {}
+ if self._is_failed(status, task_name):
+ continue
+ for asset in assets.values():
+ if asset is not None:
+ links[asset.name] = asset.browser_download_url
+
+ if links:
+ page_content = self._generate_page(links)
+ tasks[task_name] = {'index.html': page_content}
+
+ files[str(job.date)] = tasks
+
+ # write the most recent wheels under the latest directory
+ if 'latest' not in files:
+ files['latest'] = tasks
+
+ return files
+
+ def render_pypi_simple(self):
+ click.echo('\n\nRENDERING PYPI')
+
+ wheels = {}
+ for job in self.jobs:
+ click.echo('\nJOB: {}'.format(job.branch))
+
+ it = job.query_assets(ignore_prefix='test')
+ for task_name, task, status, assets in it:
+ if not task_name.startswith('wheel'):
+ continue
+ if self._is_failed(status, task_name):
+ continue
+ for asset in assets.values():
+ if asset is not None:
+ wheels[asset.name] = asset.browser_download_url
+
+ return {'pyarrow': {'index.html': self._generate_page(wheels)}}
+
+ def render(self):
+ # directory structure for the github pages, only wheels are supported
+ # at the moment
+ files = self._generate_toc({
+ 'nightly': self.render_nightlies(),
+ 'pypi': self.render_pypi_simple(),
+ })
+ files['.nojekyll'] = ''
+ return files
+
+
# configure yaml serializer
yaml = YAML()
yaml.register_class(Job)
@@ -1251,6 +1424,59 @@ def report(obj, job_name, sender_name, sender_email, recipient_email,
report.show(output)
+def github_page(ctx):
+ # currently We only list links to nightly binary wheels
+ pass
+
+
+@github_page.command('generate')
[email protected]('-n', default=10,
+ help='Number of most recent jobs')
[email protected]('--gh-branch', default='gh-pages',
+ help='Github pages branch')
[email protected]('--job-prefix', default='nightly',
+ help='Job/tag prefix the wheel links should be generated for')
[email protected]('--dry-run/--push', default=False,
+ help='Just render the files without pushing')
[email protected]('--github-push-token', '-t', default=None,
+ help='OAuth token for GitHub authentication only used for '
+ 'pushing to the crossbow repository, the API requests '
+ 'will consume the token passed to the top level crossbow '
+ 'command.')
+def generate_github_page(ctx, n, gh_branch, job_prefix, dry_run,
+ github_push_token):
+ queue = ctx.obj['queue']
+ queue.fetch()
+
+ # fail early if the requested branch is not available in the local checkout
+ remote = 'origin'
+ branch = queue.repo.branches['{}/{}'.format(remote, gh_branch)]
+ head = queue.repo[branch.target]
+
+ # $ at the end of the pattern is important because we're only looking for
+ # branches belonging to jobs not branches belonging to tasks
+ # the branches we're looking for are like 2020-01-01-0
+ jobs = queue.jobs(pattern=r"^nightly-(\d{4})-(\d{2})-(\d{2})-(\d+)$")
+ page = GithubPage(toolz.take(n, jobs))
+ files = page.render()
+ files.update(unflatten_tree(_default_tree))
+
+ if dry_run:
+ click.echo(files)
+ return
+
+ refname = 'refs/heads/{}'.format(gh_branch)
+ message = 'Update nightly wheel links {}'.format(date.today())
+ commit = queue.create_commit(files, parents=[head.id], message=message,
+ reference_name=refname)
+ click.echo('Updated `{}` branch\'s head to `{}`'
+ .format(gh_branch, commit.id))
+ queue.push([refname], github_token=github_push_token)
+
+
@crossbow.command()
@click.argument('job-name', required=True)
@click.option('-t', '--target-dir',