EE port of https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/10560/commits and https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/10563