Commit 98e0631e authored by Tom Pillot's avatar Tom Pillot
Browse files

Use logger

parent 4ae77748
......@@ -142,12 +142,19 @@ LOGGING = {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.security.DisallowedHost': {
'handlers': ['null'],
'propagate': False,
},
'gh': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
......
......@@ -26,7 +26,7 @@ from rainboard.models import Namespace, Project
from rainboard.utils import SOURCES
from . import models
logger = logging.getLogger('gh.views')
logger = logging.getLogger(__name__)
def check_suite(request: HttpRequest, rep: str) -> HttpResponse:
......@@ -41,19 +41,19 @@ def pull_request(request: HttpRequest, rep: str) -> HttpResponse:
data = loads(request.body.decode())
event = data['action']
branch = f'pr/{data["number"]}'
print(f'Pull request: {event}')
# namespace = get_object_or_404(Namespace, slug=slugify(data['repository']['owner']['login']))
namespace = get_object_or_404(Namespace, slug='tpillot')
project = get_object_or_404(Project, main_namespace=namespace, slug=slugify(data['repository']['name']))
git_repo = project.git()
logger.debug(f'{namespace.slug}/{project.slug}: Pull request on {branch}: {event}')
# Prevent pull requests on master when necessary
if event in ['opened', 'reopened']:
pr = project.github().get_pull(data["number"])
pr_branch = pr.base.ref
if not project.accept_pr_to_master and pr_branch == 'master':
print(f"New pr {data['number']} to master")
logger.info(f"{namespace.slug}/{project.slug}: New pr {data['number']} to master")
pr.create_issue_comment("This project doesn't accept pull requests on master, please change the base "
"branch of your pull request to devel.")
......@@ -80,11 +80,11 @@ def pull_request(request: HttpRequest, rep: str) -> HttpResponse:
git_repo.create_remote(gl_remote_name, url=project.remote_url_gitlab())
# Push the changes to gitlab
print(f'Pushing {commit} on {branch} on gitlab')
logger.info(f'{namespace.slug}/{project.slug}: Pushing {commit} on {branch} on gitlab')
try:
git_repo.git.push(gl_remote_name, branch)
except git.exc.GitCommandError:
print(f'Failed to push on {branch}, trying to force push.')
logger.warning(f'{namespace.slug}/{project.slug}: Failed to push on {branch} on gitlab, force pushing ...')
git_repo.git.push(gl_remote_name, branch, force=True)
# The pull request was closed, delete the branch pr/XX on Gitlab
......@@ -93,7 +93,7 @@ def pull_request(request: HttpRequest, rep: str) -> HttpResponse:
git_repo.delete_head(branch, force=True)
git_repo.delete_remote(gh_remote_name)
project.gitlab().branches.delete(branch)
print(f'Deleted branch {branch}')
logger.info(f'{namespace.slug}/{project.slug}: Deleted branch {branch}')
return HttpResponse(rep)
......@@ -109,7 +109,7 @@ def push(request: HttpRequest, source: SOURCES, rep: str) -> HttpResponse:
gl_remote_name = f'gitlab/{namespace.slug}'
gh_remote_name = f'github/{namespace.slug}'
git_repo = project.git()
print(f'Push detected on {source.name}: {branch} (commit {commit})')
logger.debug(f'{namespace.slug}/{project.slug}: Push detected on {source.name} {branch} (commit {commit})')
if branch.startswith('pr/'): # Don't sync pr/XX branches here, they are already handled by pull_request()
return HttpResponse(rep)
......@@ -136,14 +136,14 @@ def push(request: HttpRequest, source: SOURCES, rep: str) -> HttpResponse:
project.github().get_git_ref(f'heads/{branch}').delete()
else:
project.gitlab().branches.delete(branch)
print(f"Deleted branch {branch}")
logger.info(f'{namespace.slug}/{project.slug}: Deleted branch {branch}')
return HttpResponse(rep)
# Make sure we fetched the latest commit
ref = gl_remote.refs[branch] if source == SOURCES.gitlab else gh_remote.refs[branch]
if str(ref.commit) != commit:
fail = f'Push: wrong commit: {ref.commit} vs {commit}'
print(fail)
logger.error(f'{namespace.slug}/{project.slug}: ' + fail)
return HttpResponseBadRequest(fail)
# Update the branch to the latest commit
......@@ -155,13 +155,14 @@ def push(request: HttpRequest, source: SOURCES, rep: str) -> HttpResponse:
# Push the changes to other remote
try:
if source == SOURCES.gitlab and (branch not in gh_remote.refs or str(gh_remote.refs[branch].commit) != commit):
print(f'Pushing {commit} on {branch} on github.')
logger.info(f'{namespace.slug}/{project.slug}: Pushing {commit} on {branch} on github')
git_repo.git.push(gh_remote_name, branch)
elif branch not in gl_remote.refs or str(gl_remote.refs[branch].commit) != commit:
print(f'Pushing {commit} on {branch} on gitlab.')
logger.info(f'{namespace.slug}/{project.slug}: Pushing {commit} on {branch} on gitlab')
git_repo.git.push(gl_remote_name, branch)
except git.exc.GitCommandError:
# Probably failed because of a force push
logger.exception(f'{namespace.slug}/{project.slug}: Forge sync failed')
message = traceback.format_exc()
message = re.sub(r'://.*@', '://[REDACTED]@', message) # Hide access tokens in the mail
mail_admins(f'Forge sync failed for {namespace.slug}/{project.slug}', message)
......@@ -174,13 +175,13 @@ def pipeline(request: HttpRequest, rep: str) -> HttpResponse:
"""Something happened on a Gitlab pipeline. Tell Github if necessary."""
data = loads(request.body.decode())
branch, commit, gl_status, pipeline_id = (data['object_attributes'][key] for key in ['ref', 'sha', 'status', 'id'])
print(f'Pipeline id #{pipeline_id} on commit {commit} for branch {branch}, status: {gl_status}')
# namespace = get_object_or_404(Namespace, slug=slugify(data['project']['namespace']))
namespace = get_object_or_404(Namespace, slug='tpillot')
project = get_object_or_404(Project, main_namespace=namespace, slug=slugify(data['project']['name']))
gh_repo = project.github()
ci_web_url = project.url_gitlab() + '/pipelines/' + str(pipeline_id)
logger.debug(f'{namespace.slug}/{project.slug}: Pipeline #{pipeline_id} on commit {commit} for branch {branch}, '
f'status: {gl_status}')
# Report the status to Github
if gl_status in ['pending', 'success', 'failed']:
......@@ -194,7 +195,7 @@ def pipeline(request: HttpRequest, rep: str) -> HttpResponse:
except github.GithubException as e:
if e.status == 404:
# Happens when a new branch is created on gitlab and the pipeline event comes before the push event
print(f"Branch {branch} does not exist on github, unable to report the pipeline status.")
logger.warning(f"Branch {branch} does not exist on github, unable to report the pipeline status.")
else:
raise
......@@ -212,22 +213,22 @@ def webhook(request: HttpRequest) -> HttpResponse:
forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR').split(', ')[0]
networks = requests.get('https://api.github.com/meta').json()['hooks']
if not any(ip_address(forwarded_for) in ip_network(net) for net in networks):
print('not from github IP')
logger.warning('not from github IP')
return HttpResponseRedirect(reverse('login'))
# validate signature
signature = request.META.get('HTTP_X_HUB_SIGNATURE')
if signature is None:
print('no signature')
logger.warning('no signature')
return HttpResponseRedirect(reverse('login'))
algo, signature = signature.split('=')
if algo != 'sha1':
print('signature not sha-1')
logger.warning('signature not sha-1')
return HttpResponseServerError('I only speak sha1.', status=501)
mac = hmac.new(force_bytes(settings.GITHUB_WEBHOOK_KEY), msg=force_bytes(request.body), digestmod=sha1)
if not hmac.compare_digest(force_bytes(mac.hexdigest()), force_bytes(signature)):
print('wrong signature')
logger.warning('wrong signature')
return HttpResponseForbidden('wrong signature.')
# process event
......@@ -251,16 +252,16 @@ def gl_webhook(request: HttpRequest) -> HttpResponse:
# validate ip source
if not ip_laas(request):
print('not from LAAS IP')
logger.warning('not from LAAS IP')
return HttpResponseRedirect(reverse('login'))
# validate token
token = request.META.get('HTTP_X_GITLAB_TOKEN')
if token is None:
print('no token')
logger.warning('no token')
return HttpResponseRedirect(reverse('login'))
if token != settings.GITLAB_WEBHOOK_KEY:
print('wrong token')
logger.warning('wrong token')
return HttpResponseForbidden('wrong token.')
event = request.META.get('HTTP_X_GITLAB_EVENT', 'ping')
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment