def get_keystone_manager(endpoint, token, api_version=None):
    """Return a keystonemanager for the correct API version

    If api_version has not been set then create a manager based on the endpoint
    Use this manager to query the catalogue and determine which api version
    should actually be being used. Return the correct client based on that.
    Function is wrapped in a retry_on_exception to catch the case where the
    keystone service is still initialising and not responding to requests yet.
    XXX I think the keystone client should be able to do version
        detection automatically so the code below could be greatly
        simplified

    @param endpoint: the keystone endpoint to point client at
    @param token: the keystone admin_token
    @param api_version: version of the keystone api the client should use
    @returns keystonemanager class used for interrogating keystone
    """
    if api_version:
        return _get_keystone_manager_class(endpoint, token, api_version)
    else:
        if 'v2.0' in endpoint.split('/'):
            manager = _get_keystone_manager_class(endpoint, token, 2)
        else:
            manager = _get_keystone_manager_class(endpoint, token, 3)
        if endpoint.endswith('/'):
            base_ep = endpoint.rsplit('/', 2)[0]
        else:
            base_ep = endpoint.rsplit('/', 1)[0]
        svc_id = None
        for svc in manager.api.services.list():
            if svc.type == 'identity':
                svc_id = svc.id
        version = None
        for ep in manager.api.endpoints.list():
            if ep.service_id == svc_id and hasattr(ep, 'adminurl'):
                version = ep.adminurl.split('/')[-1]
        if version and version == 'v2.0':
            new_ep = base_ep + "/" + 'v2.0'
            return _get_keystone_manager_class(new_ep, token, 2)
        elif version and version == 'v3':
            new_ep = base_ep + "/" + 'v3'
            return _get_keystone_manager_class(new_ep, token, 3)
        else:
            return manager