Exemplo n.º 1
0
async def create_controller(c_type, name, region, cred_name):
    try:
        logger.info('Adding controller to database')
        token = JuJu_Token()
        datastore.create_controller(name, c_type, region, cred_name)
        datastore.add_user_to_controller(name, 'admin', 'superuser')

        logger.info('Bootstrapping controller')
        credential = juju.get_credential(token.username, cred_name)
        logger.info('credential found %s:', credential['credential'])
        juju.get_controller_types()[c_type].create_controller(name, region, credential['credential'], 't{}'.format(hashlib.md5(cred_name.encode('utf')).hexdigest()))
        pswd = token.password

        logger.info('Setting admin password')
        check_output(['juju', 'change-user-password', 'admin', '-c', name],
                     input=bytes('{}\n{}\n'.format(pswd, pswd), 'utf-8'))

        logger.info('Updating controller in database')
        with open(os.path.join(str(Path.home()), '.local', 'share', 'juju', 'controllers.yaml'), 'r') as data:
            con_data = yaml.load(data)
        datastore.set_controller_state(
            name,
            'ready',
            con_data['controllers'][name]['api-endpoints'],
            con_data['controllers'][name]['uuid'],
            con_data['controllers'][name]['ca-cert'])

        logger.info('Connecting to controller')
        controller = juju.Controller_Connection(token, name)

        logger.info('Adding existing credentials and models to database')
        credentials = datastore.get_credentials(token.username)
        async with controller.connect(token) as juju_con:
            for cred in credentials:
                if cred['name'] != cred_name:
                    credential_name = 't{}'.format(hashlib.md5(cred_name.encode('utf')).hexdigest())
                    cloud_facade = client.CloudFacade.from_connection(juju_con.connection)
                    credential = juju.generate_cred_file(c_type, credential_name, cred['credential'])
                    cloud_cred = client.UpdateCloudCredential(
                        client.CloudCredential(credential['key'], credential['type']),
                        tag.credential(c_type, token.username, credential_name)
                    )
                    await cloud_facade.UpdateCredentials([cloud_cred])
            models = await juju_con.get_models()
            for model in models.serialize()['user-models']:
                model = model.serialize()['model'].serialize()
                datastore.add_model_to_controller(name, model['name'])
                datastore.set_model_state(name, model['name'], 'ready', credential=cred_name, uuid=model['uuid'])
                datastore.set_model_access(name, model['name'], token.username, 'admin')
        logger.info('Controller succesfully created!')
    except Exception:  #pylint: disable=W0703
        datastore.destroy_controller(name)
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        for l in lines:
            logger.error(l)
        datastore.set_controller_state(name, 'error')
Exemplo n.º 2
0
def update_controller_database(c_name):
    """Sets the controller to ready state. This function should be executed
    after the bootstrap of the controller."""
    controllers_yaml = os.path.join(str(Path.home()), '.local', 'share',
                                    'juju', 'controllers.yaml')
    with open(controllers_yaml, 'r') as data:
        con_data = yaml.load(data)
    datastore.set_controller_state(
        c_name, 'ready', con_data['controllers'][c_name]['api-endpoints'],
        con_data['controllers'][c_name]['uuid'],
        con_data['controllers'][c_name]['ca-cert'])
    return con_data
Exemplo n.º 3
0
async def create_controller(c_type, name, region, credentials):
    try:
        logger.info('Adding controller to database')
        datastore.create_controller(name, c_type, region)
        datastore.add_user_to_controller(name, 'admin', 'superuser')
        logger.info('Bootstrapping controller')
        juju.get_controller_types()[c_type].create_controller(
            name, region, credentials)
        pswd = settings.JUJU_ADMIN_PASSWORD
        logger.info('Setting admin password')
        check_output(['juju', 'change-user-password', 'admin', '-c', name],
                     input=bytes('{}\n{}\n'.format(pswd, pswd), 'utf-8'))
        logger.info('Updating controller in database')
        with open(
                os.path.join(str(Path.home()), '.local', 'share', 'juju',
                             'controllers.yaml'), 'r') as data:
            con_data = yaml.load(data)
        datastore.set_controller_state(
            name, 'ready', con_data['controllers'][name]['api-endpoints'],
            con_data['controllers'][name]['uuid'],
            con_data['controllers'][name]['ca-cert'])
        token = JuJu_Token()
        logger.info('Connecting to controller')
        controller = juju.Controller_Connection(token, name)
        logger.info('Adding credentials to database')
        result_cred = await juju.generate_cred_file(c_type, 'admin',
                                                    credentials)
        datastore.add_credential('admin', result_cred)
        logger.info('Adding existing models to database')
        async with controller.connect(token) as juju_con:
            models = await juju_con.get_models()
            for model in models.serialize()['user-models']:
                model = model.serialize()['model'].serialize()
                datastore.add_model_to_controller(name, model['name'])
                datastore.set_model_state(name, model['name'], 'ready',
                                          model['uuid'])
                datastore.set_model_access(name, model['name'], token.username,
                                           'admin')
    except Exception:  #pylint: disable=W0703
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        for l in lines:
            logger.error(l)
        datastore.set_controller_state(name, 'error')
Exemplo n.º 4
0
async def bootstrap_azure_controller(c_name, region, cred_name, username,
                                     password):
    try:
        tengu_username = settings.JUJU_ADMIN_USER
        tengu_password = settings.JUJU_ADMIN_PASSWORD
        juju_cred_name = 't{}'.format(
            hashlib.md5(cred_name.encode('utf')).hexdigest())
        credential = juju.get_credential(username, cred_name)

        # Check if the credential is valid.
        juju.get_controller_types()['azure'].check_valid_credentials(
            credential)

        temp_cred = create_temporary_cred_file(juju_cred_name, credential)

        logger.info('Adding credential to JuJu...')
        check_call(
            ['juju', 'add-credential', 'azure', '-f', temp_cred, '--replace'])

        logger.info('Bootstrapping controller in Azure cloud...')
        check_call([
            'juju', 'bootstrap', '--agent-version=2.3.0', 'azure', c_name,
            '--credential', juju_cred_name
        ])

        # Remove temporary credentials.
        os.remove(temp_cred)

        logger.info('Setting admin password...')
        check_output(['juju', 'change-user-password', 'admin', '-c', c_name],
                     input=bytes(
                         '{}\n{}\n'.format(tengu_password, tengu_password),
                         'utf-8'))

        logger.info('Updating controller in database...')
        con_data = update_controller_database(c_name)

        logger.info('Connecting to controller...')
        controller = Controller()
        await controller.connect(
            con_data['controllers'][c_name]['api-endpoints'][0],
            tengu_username, tengu_password,
            con_data['controllers'][c_name]['ca-cert'])

        user_info = datastore.get_user(username)
        juju_username = user_info["juju_username"]
        user = tag.user(juju_username)

        logger.info('Adding existing credentials to new controller...')
        await update_credentials_new_controller(controller, username,
                                                juju_username, cred_name)

        model_facade = client.ModelManagerFacade.from_connection(
            controller.connection)
        controller_facade = client.ControllerFacade.from_connection(
            controller.connection)
        if username != tengu_username:
            user_facade = client.UserManagerFacade.from_connection(
                controller.connection)
            users = [
                client.AddUser(display_name=juju_username,
                               username=juju_username,
                               password=password)
            ]
            await user_facade.AddUser(users)
            changes = client.ModifyControllerAccess('superuser', 'grant', user)
            await controller_facade.ModifyControllerAccess([changes])

        logger.info('Adding default models to database...')
        await add_default_models_to_database(c_name, cred_name, username,
                                             juju_username, controller,
                                             user_info)

        logger.info('Controller succesfully created!')
    except Exception:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        for l in lines:
            logger.error(l)
        datastore.set_controller_state(c_name, 'error')
    finally:
        if 'controller' in locals():
            await juju.disconnect(controller)
Exemplo n.º 5
0
async def bootstrap_aws_controller(c_name, region, cred_name, username,
                                   password):  #pylint: disable=E0001
    try:
        # Check if the credential is valid.
        tengu_username = settings.JUJU_ADMIN_USER
        tengu_password = settings.JUJU_ADMIN_PASSWORD
        valid_cred_name = 't{}'.format(
            hashlib.md5(cred_name.encode('utf')).hexdigest())
        credential = juju.get_credential(username, cred_name)
        logger.info(credential)

        juju.get_controller_types()['aws'].check_valid_credentials(credential)

        # Create credential file that can be used to bootstrap controller.
        cred_path = '/home/{}/credentials'.format(settings.SOJOBO_USER)
        if not os.path.exists(cred_path):
            os.mkdir(cred_path)
        filepath = '{}/aws-{}.json'.format(cred_path, valid_cred_name)
        with open(filepath, 'w+') as credfile:
            json.dump(credential['credential'], credfile)
        path = '/tmp/credentials.yaml'
        data = {
            'credentials': {
                'aws': {
                    valid_cred_name: {
                        'auth-type': 'access-key',
                        'access-key': credential['credential']['access-key'],
                        'secret-key': credential['credential']['secret-key']
                    }
                }
            }
        }
        with open(path, 'w') as dest:
            yaml.dump(data, dest, default_flow_style=True)
        logger.info(valid_cred_name)
        logger.info(data)
        check_call(['juju', 'add-credential', 'aws', '-f', path, '--replace'])
        logger.info(path)
        check_call([
            'juju', 'bootstrap', '--agent-version=2.3.0',
            'aws/{}'.format(region), c_name, '--credential', valid_cred_name
        ])
        os.remove(path)

        logger.info('Setting admin password')
        check_output(['juju', 'change-user-password', 'admin', '-c', c_name],
                     input=bytes(
                         '{}\n{}\n'.format(tengu_password, tengu_password),
                         'utf-8'))

        con_data = {}
        logger.info('Updating controller in database')
        with open(
                os.path.join(str(Path.home()), '.local', 'share', 'juju',
                             'controllers.yaml'), 'r') as data:
            con_data = yaml.load(data)
        datastore.set_controller_state(
            c_name,
            'ready',
            endpoints=con_data['controllers'][c_name]['api-endpoints'],
            uuid=con_data['controllers'][c_name]['uuid'],
            ca_cert=con_data['controllers'][c_name]['ca-cert'])

        logger.info('Connecting to controller')
        controller = Controller()

        logger.info(
            'Adding existing credentials and default models to database...')
        credentials = datastore.get_cloud_credentials('aws', username)
        logger.info(credentials)
        await controller.connect(
            endpoint=con_data['controllers'][c_name]['api-endpoints'][0],
            username=tengu_username,
            password=tengu_password,
            cacert=con_data['controllers'][c_name]['ca-cert'])
        user_info = datastore.get_user(username)
        juju_username = user_info["juju_username"]
        for cred in credentials:
            if username != tengu_username:
                await juju.update_cloud(controller, 'aws', cred['name'],
                                        juju_username, username)
                logger.info('Added credential %s to controller %s',
                            cred['name'], c_name)
            elif cred['name'] != cred_name:
                await juju.update_cloud(controller, 'aws', cred['name'],
                                        juju_username, username)
        user = tag.user(juju_username)
        model_facade = client.ModelManagerFacade.from_connection(
            controller.connection)
        controller_facade = client.ControllerFacade.from_connection(
            controller.connection)
        if username != tengu_username:
            user_facade = client.UserManagerFacade.from_connection(
                controller.connection)
            users = [
                client.AddUser(display_name=juju_username,
                               username=juju_username,
                               password=password)
            ]
            await user_facade.AddUser(users)
            changes = client.ModifyControllerAccess('superuser', 'grant', user)
            await controller_facade.ModifyControllerAccess([changes])

        c_info = datastore.get_controller(c_name)
        models = await controller_facade.AllModels()
        for model in models.user_models:
            if model:
                m_key = juju.construct_model_key(c_info['name'],
                                                 model.model.name)
                logger.info(model.model.name)
                if username != tengu_username:
                    model_tag = tag.model(model.model.uuid)
                    changes = client.ModifyModelAccess('admin', 'grant',
                                                       model_tag, user)
                    await model_facade.ModifyModelAccess([changes])
                datastore.create_model(m_key,
                                       model.model.name,
                                       state='Model is being deployed',
                                       uuid='')
                datastore.add_model_to_controller(c_name, m_key)
                datastore.set_model_state(m_key,
                                          'ready',
                                          credential=cred_name,
                                          uuid=model.model.uuid)
                datastore.set_model_access(m_key, username, 'admin')
                ssh_keys = user_info["ssh_keys"]
                if len(ssh_keys) > 0:
                    juju.update_ssh_keys_model(username, ssh_keys, c_name,
                                               m_key)
        logger.info('Controller succesfully created!')
    except Exception:  #pylint: disable=W0703
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        for l in lines:
            logger.error(l)
        datastore.set_controller_state(c_name, 'error')
    finally:
        if 'controller' in locals():
            await juju.disconnect(controller)