Exemplo n.º 1
0
def get_secret(key='ADMINPASSWORD', create=True):
    horton = utils.Horton()
    assert key in ['ADMINPASSWORD', 'MASTERKEY']
    if key in horton.cache and horton.cache[key]:
        return horton.cache[key]
    else:
        if create:
            length = 15 if key[0] == 'A' else 50
            secret = generate_password(length)
            horton.cache[key] = secret
            return secret
        else:
            return None
Exemplo n.º 2
0
import six
import uuid
from whoville import config, utils, security, infra
import cloudera.director.latest as cd
from cloudera.director.common.rest import ApiException

__all__ = [
    'list_environments', 'get_environment', 'create_environment',
    'delete_environment', 'create_deployment', 'list_deployments',
    'delete_deployment', 'get_deployment', 'get_deployment_status',
    'list_clusters', 'create_instance_template', 'get_instance_template',
    'get_cluster', 'create_cluster', 'create_virtual_instance'
]

log = logging.getLogger(__name__)
horton = utils.Horton()


def get_environment(env_name=None):
    tgt_env_name = env_name if env_name else horton.namespace + 'whoville'
    envs = list_environments()
    if tgt_env_name in envs:
        env_test = cd.EnvironmentsApi(horton.cad).get_redacted(tgt_env_name)
        while not env_test:
            sleep(2)
            env_test = cd.EnvironmentsApi(
                horton.cad).get_redacted(tgt_env_name)
        return env_test
    else:
        return create_environment()
Exemplo n.º 3
0
def service_login(service='cloudbreak',
                  username=None,
                  password=None,
                  bool_response=False):
    """
    Login to the currently configured server.

    Login requires a secure connection over https.
    Prior to calling this method, the host must be specified
    and the SSLContext should be configured (if necessary).

    Successful login will result in a generated token (JWT) being
    cached in the api_client config that will be passed in all future
    REST API calls. To clear that token, call service_logout.

    The token is temporary and will expire after a duration set by
    the server. After a token expires, you must call
    this method again to generate a new token.

    Args:
        service (str): 'cloudbreak'; the service to login to
        username (str): The username to submit
        password (str): The password to use
        bool_response (bool): If True, the function will return False instead
            of an error. Useful for connection testing.

    Returns:
        (bool): True if successful, False or an Error if not. See bool_response

    """
    log_args = locals()
    horton = utils.Horton()
    _ = log_args.pop('password')
    log.info("Called service_login with args %s", log_args)
    assert service in _valid_services
    assert isinstance(username, six.string_types)
    assert isinstance(password, six.string_types)
    assert isinstance(bool_response, bool)

    if service == 'cloudbreak':
        configuration = config.cb_config
    elif service == 'director':
        configuration = config.cd_config
    else:
        raise ValueError("Unrecognised Service parameter")

    assert configuration.host, "Host must be set prior to logging in."
    assert configuration.host.startswith("https"), \
        "Login is only available when connecting over HTTPS."

    if service == 'director':
        config.cd_config.username = username
        config.cd_config.password = password
        horton.cad = ApiClient(configuration=config.cd_config)
        return True
    if service == 'cloudbreak':
        url = config.cb_config.host.replace('/cb/api',
                                            '/identity/oauth/authorize')
        redirect_uri = config.cb_config.host.replace('/cb/api', '/authorize')
        resp = requests.post(
            url=url,
            params={
                'response_type': 'token',
                'client_id': 'cloudbreak_shell',
                'scope.0': 'openid',
                'source': 'login',
                'redirect_uri': 'http://cloudbreak.shell'
            },
            headers={'accept': 'application/x-www-form-urlencoded'},
            verify=config.cb_config.verify_ssl,
            allow_redirects=False,
            data=[
                ('credentials', '{"username":"******",'
                 '"password":"******"}'),
            ])
        if 'Location' not in resp.headers:
            raise ValueError("Login Failed, please check Cloudbreak and your"
                             "Credentials")
        try:
            token = parse.parse_qs(resp.headers['Location'])['access_token'][0]
            # Todo: get the expiry and set into config as well
            # Todo: use expiry to refresh the token as required
            # Todo: Find approach to auto fetch the token as required
        except KeyError:
            if bool_response:
                return False
            raise ConnectionError("No Access Token in server response. Please "
                                  "check your Auth config and environment.")
        set_service_auth_token(token=token, service='cloudbreak')
        return True