EE port of https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/17356
Extracted from https://gitlab.com/gitlab-org/gitlab-ee/merge_requests/4720