spark-instrumented-optimizer/dev/github_jira_sync.py
Yuming Wang c8f56eb7bb [MINOR] Fix usage print to guide pip3 to install jira-python library
### What changes were proposed in this pull request?

Use `pip3` to install `jira-python` library.

### Why are the changes needed?

We use python3 in the build script and `pip` is missing by default.

```
yumwangLM-SHC-16508156 spark % sw_vers
ProductName:	Mac OS X
ProductVersion:	10.15.6
BuildVersion:	19G2021

yumwangLM-SHC-16508156 spark % sudo pip install jira
Password:
sudo: pip: command not found
```

### Does this PR introduce _any_ user-facing change?

No.

### How was this patch tested?

Manual test:
```
yumwangLM-SHC-16508156 spark % sudo pip3 install jira
WARNING: The directory '/Users/yumwang/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting jira
  Downloading jira-2.0.0-py2.py3-none-any.whl (57 kB)
     |████████████████████████████████| 57 kB 78 kB/s
Requirement already satisfied: setuptools>=20.10.1 in /usr/local/lib/python3.8/site-packages (from jira) (49.2.0)
Collecting six>=1.10.0
  Downloading six-1.15.0-py2.py3-none-any.whl (10 kB)
Collecting defusedxml
  Downloading defusedxml-0.6.0-py2.py3-none-any.whl (23 kB)
Collecting oauthlib[signedtoken]>=1.0.0
  Downloading oauthlib-3.1.0-py2.py3-none-any.whl (147 kB)
     |████████████████████████████████| 147 kB 306 kB/s
Collecting pbr>=3.0.0
  Downloading pbr-5.5.0-py2.py3-none-any.whl (106 kB)
     |████████████████████████████████| 106 kB 345 kB/s
Collecting requests-toolbelt
  Downloading requests_toolbelt-0.9.1-py2.py3-none-any.whl (54 kB)
     |████████████████████████████████| 54 kB 474 kB/s
Collecting requests-oauthlib>=0.6.1
  Downloading requests_oauthlib-1.3.0-py2.py3-none-any.whl (23 kB)
Collecting requests>=2.10.0
  Downloading requests-2.24.0-py2.py3-none-any.whl (61 kB)
     |████████████████████████████████| 61 kB 521 kB/s
Collecting cryptography; extra == "signedtoken"
  Downloading cryptography-3.1-cp35-abi3-macosx_10_10_x86_64.whl (1.8 MB)
     |████████████████████████████████| 1.8 MB 497 kB/s
Collecting pyjwt>=1.0.0; extra == "signedtoken"
  Downloading PyJWT-1.7.1-py2.py3-none-any.whl (18 kB)
Collecting chardet<4,>=3.0.2
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB)
     |████████████████████████████████| 133 kB 671 kB/s
Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1
  Downloading urllib3-1.25.10-py2.py3-none-any.whl (127 kB)
     |████████████████████████████████| 127 kB 930 kB/s
Collecting certifi>=2017.4.17
  Downloading certifi-2020.6.20-py2.py3-none-any.whl (156 kB)
     |████████████████████████████████| 156 kB 7.1 MB/s
Collecting idna<3,>=2.5
  Downloading idna-2.10-py2.py3-none-any.whl (58 kB)
     |████████████████████████████████| 58 kB 1.3 MB/s
Collecting cffi!=1.11.3,>=1.8
  Downloading cffi-1.14.2-cp38-cp38-macosx_10_9_x86_64.whl (176 kB)
     |████████████████████████████████| 176 kB 7.3 MB/s
Collecting pycparser
  Downloading pycparser-2.20-py2.py3-none-any.whl (112 kB)
     |████████████████████████████████| 112 kB 773 kB/s
Installing collected packages: six, defusedxml, pycparser, cffi, cryptography, pyjwt, oauthlib, pbr, chardet, urllib3, certifi, idna, requests, requests-toolbelt, requests-oauthlib, jira
Successfully installed certifi-2020.6.20 cffi-1.14.2 chardet-3.0.4 cryptography-3.1 defusedxml-0.6.0 idna-2.10 jira-2.0.0 oauthlib-3.1.0 pbr-5.5.0 pycparser-2.20 pyjwt-1.7.1 requests-2.24.0 requests-oauthlib-1.3.0 requests-toolbelt-0.9.1 six-1.15.0 urllib3-1.25.10
```

Closes #29628 from wangyum/jira.

Authored-by: Yuming Wang <yumwang@ebay.com>
Signed-off-by: HyukjinKwon <gurwls223@apache.org>
2020-09-03 01:10:59 +09:00

202 lines
7 KiB
Python
Executable file

#!/usr/bin/env python3
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Utility for updating JIRA's with information about Github pull requests
import json
import os
import re
import sys
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import HTTPError
try:
import jira.client
except ImportError:
print("This tool requires the jira-python library")
print("Install using 'sudo pip3 install jira'")
sys.exit(-1)
# User facing configs
GITHUB_API_BASE = os.environ.get("GITHUB_API_BASE", "https://api.github.com/repos/apache/spark")
GITHUB_OAUTH_KEY = os.environ.get("GITHUB_OAUTH_KEY")
JIRA_PROJECT_NAME = os.environ.get("JIRA_PROJECT_NAME", "SPARK")
JIRA_API_BASE = os.environ.get("JIRA_API_BASE", "https://issues.apache.org/jira")
JIRA_USERNAME = os.environ.get("JIRA_USERNAME", "apachespark")
JIRA_PASSWORD = os.environ.get("JIRA_PASSWORD", "XXX")
# Maximum number of updates to perform in one run
MAX_UPDATES = int(os.environ.get("MAX_UPDATES", "100000"))
# Cut-off for oldest PR on which to comment. Useful for avoiding
# "notification overload" when running for the first time.
MIN_COMMENT_PR = int(os.environ.get("MIN_COMMENT_PR", "1496"))
# File used as an optimization to store maximum previously seen PR
# Used mostly because accessing ASF JIRA is slow, so we want to avoid checking
# the state of JIRA's that are tied to PR's we've already looked at.
MAX_FILE = ".github-jira-max"
def get_url(url):
try:
request = Request(url)
request.add_header('Authorization', 'token %s' % GITHUB_OAUTH_KEY)
return urlopen(request)
except HTTPError:
print("Unable to fetch URL, exiting: %s" % url)
sys.exit(-1)
def get_json(urllib_response):
return json.loads(urllib_response.read().decode("utf-8"))
# Return a list of (JIRA id, JSON dict) tuples:
# e.g. [('SPARK-1234', {.. json ..}), ('SPARK-5687', {.. json ..})}
def get_jira_prs():
result = []
has_next_page = True
page_num = 0
while has_next_page:
page = get_url(GITHUB_API_BASE + "/pulls?page=%s&per_page=100" % page_num)
page_json = get_json(page)
for pull in page_json:
jiras = re.findall(JIRA_PROJECT_NAME + "-[0-9]{4,5}", pull['title'])
for jira in jiras:
result = result + [(jira, pull)]
# Check if there is another page
link_headers = list(filter(lambda k: k.startswith("Link"), page.headers))
if not link_headers or "next" not in link_headers[0]:
has_next_page = False
else:
page_num += 1
return result
def set_max_pr(max_val):
f = open(MAX_FILE, 'w')
f.write("%s" % max_val)
f.close()
print("Writing largest PR number seen: %s" % max_val)
def get_max_pr():
if os.path.exists(MAX_FILE):
result = int(open(MAX_FILE, 'r').read())
print("Read largest PR number previously seen: %s" % result)
return result
else:
return 0
def build_pr_component_dic(jira_prs):
print("Build PR dictionary")
dic = {}
for issue, pr in jira_prs:
print(issue)
page = get_json(get_url(JIRA_API_BASE + "/rest/api/2/issue/" + issue))
jira_components = [c['name'].upper() for c in page['fields']['components']]
if pr['number'] in dic:
dic[pr['number']][1].update(jira_components)
else:
pr_components = set(label['name'].upper() for label in pr['labels'])
dic[pr['number']] = (pr_components, set(jira_components))
return dic
def reset_pr_labels(pr_num, jira_components):
url = '%s/issues/%s/labels' % (GITHUB_API_BASE, pr_num)
labels = ', '.join(('"%s"' % c) for c in jira_components)
try:
request = Request(url, data=('{"labels":[%s]}' % labels).encode('utf-8'))
request.add_header('Content-Type', 'application/json')
request.add_header('Authorization', 'token %s' % GITHUB_OAUTH_KEY)
request.get_method = lambda: 'PUT'
urlopen(request)
print("Set %s with labels %s" % (pr_num, labels))
except HTTPError:
print("Unable to update PR labels, exiting: %s" % url)
sys.exit(-1)
jira_client = jira.client.JIRA({'server': JIRA_API_BASE},
basic_auth=(JIRA_USERNAME, JIRA_PASSWORD))
jira_prs = get_jira_prs()
previous_max = get_max_pr()
print("Retrieved %s JIRA PR's from Github" % len(jira_prs))
jira_prs = [(k, v) for k, v in jira_prs if int(v['number']) > previous_max]
print("%s PR's remain after excluding visted ones" % len(jira_prs))
num_updates = 0
considered = []
for issue, pr in sorted(jira_prs, key=lambda kv: int(kv[1]['number'])):
if num_updates >= MAX_UPDATES:
break
pr_num = int(pr['number'])
print("Checking issue %s" % issue)
considered = considered + [pr_num]
url = pr['html_url']
title = "[Github] Pull Request #%s (%s)" % (pr['number'], pr['user']['login'])
try:
page = get_json(get_url(JIRA_API_BASE + "/rest/api/2/issue/" + issue + "/remotelink"))
existing_links = map(lambda l: l['object']['url'], page)
except:
print("Failure reading JIRA %s (does it exist?)" % issue)
print(sys.exc_info()[0])
continue
if url in existing_links:
continue
icon = {"title": "Pull request #%s" % pr['number'],
"url16x16": "https://assets-cdn.github.com/favicon.ico"}
destination = {"title": title, "url": url, "icon": icon}
# For all possible fields see:
# https://developer.atlassian.com/display/JIRADEV/Fields+in+Remote+Issue+Links
# application = {"name": "Github pull requests", "type": "org.apache.spark.jira.github"}
jira_client.add_remote_link(issue, destination)
comment = "User '%s' has created a pull request for this issue:" % pr['user']['login']
comment += "\n%s" % pr['html_url']
if pr_num >= MIN_COMMENT_PR:
jira_client.add_comment(issue, comment)
print("Added link %s <-> PR #%s" % (issue, pr['number']))
num_updates += 1
if len(considered) > 0:
set_max_pr(max(considered))
# Additionally, expose the JIRA labels to the PR
num_updates = 0
for pr_num, (pr_components, jira_components) in build_pr_component_dic(jira_prs).items():
print(pr_num)
if pr_components == jira_components:
continue
if num_updates >= MAX_UPDATES:
break
reset_pr_labels(pr_num, jira_components)
num_updates += 1