<commit_before>import os

from keystoneclient.exceptions import NotFound, ClientException
from keystoneclient.v3 import client as ks_client
from novaclient.v1_1 import client as nova_client

from atmosphere.logger import logger
from atmosphere import settings

"""
OpenStack CloudAdmin Libarary
    Use this library to:
    * manage users within Keystone - openstack auth
"""


class UserManager():
    keystone = None
    nova = None
    user = None
    password = <PASSWORD>
    tenant = None

    @classmethod
    def settings_init(self, *args, **kwargs):
        settings_args = {
            'username': settings.OPENSTACK_ADMIN_KEY,
            'password': settings.OPENSTACK_ADMIN_SECRET,
            'tenant_name': settings.OPENSTACK_ADMIN_TENANT,
            'auth_url': settings.OPENSTACK_ADMIN_URL,
            'region_name': settings.OPENSTACK_DEFAULT_REGION
        }
        settings_args.update(kwargs)
        manager = UserManager(*args, **settings_args)
        return manager

    @classmethod
    def lc_driver_init(self, lc_driver, region=None, *args, **kwargs):
        if not region:
            region = settings.OPENSTACK_DEFAULT_REGION
        lc_driver_args = {
            'username': lc_driver.key,
            'password': <PASSWORD>,
            'tenant_name': lc_driver._ex_tenant_name,
            'auth_url': lc_driver._ex_force_auth_url,
            'region_name': region
        }
        lc_driver_args.update(kwargs)
        manager = UserManager(*args, **lc_driver_args)
        return manager

    def __init__(self, *args, **kwargs):
        self.newConnection(*args, **kwargs)

    def newConnection(self, *args, **kwargs):
        self.keystone = ks_client.Client(*args, **kwargs)
        self.nova = nova_client.Client(kwargs.pop('username'),
                                       kwargs.pop('password'),
                                       kwargs.pop('tenant_name'),
                                       kwargs.pop('auth_url'),
                                       kwargs.pop('region_name'),
                                       *args, no_cache=True, **kwargs)
        self.nova.client.region_name = settings.OPENSTACK_DEFAULT_REGION

    ##Composite Classes##
    def add_usergroup(self, username, password,
                     createUser=True, adminRole=False):
        """
        Create a group for this user only
        then create the user
        """
        #Create tenant for user/group
        tenant = self.add_tenant(username)

        #Create user
        try:
            user = self.add_user(username, password, tenant.name)
        except ClientException as user_exists:
            logger.debug('Received Error %s on add, User exists.' %
                         user_exists)
            user = self.get_user(username)

        logger.debug("Assign Tenant:%s Member:%s Role:%s" %
                    (username, username, adminRole))
        try:
            role = self.add_tenant_member(username, username, adminRole)
        except ClientException:
            logger.warn('Could not assign role to username %s' % username)
        try:
            # keystone admin always gets access, always has admin priv.
            self.add_tenant_member(username, self.keystone.username, True)
        except ClientException:
            logger.warn('Could not assign admin role to username %s' %
                        self.keystone.username)
        return (tenant, user, role)

    def build_security_group(self, username, password, tenant_name,
            protocol_list=None, *args, **kwargs):

        nova = nova_client.Client(username,
                                  password,
                                  tenant_name,
                                  self.nova.client.auth_url,
                                  self.nova.client.region_name,
                                  *args, no_cache=True, **kwargs)
        nova.client.region_name = self.nova.client.region_name
        if not protocol_list:
            #Build a "good" one.
            protocol_list = [
                ('TCP', 22, 22),
                ('TCP', 80, 80),
                ('TCP', 5666, 5666),
                ('TCP', 5900, 5904),
                ('TCP', 4200, 4200),
                ('ICMP', -1, -1),
            ]
        #with nova.security_groups.find(name='default') as default_sec_group:
        default_sec_group = nova.security_groups.find(name='default')
        for (ip_protocol, from_port, to_port) in protocol_list:
            if not self.find_rule(default_sec_group, ip_protocol,
                    from_port, to_port):
                nova.security_group_rules.create(default_sec_group.id,
                                                 ip_protocol=ip_protocol,
                                                 from_port=from_port,
                                                 to_port=to_port)
        return nova.security_groups.find(name='default')

    def find_rule(self, security_group, ip_protocol, from_port, to_port):
        for r in security_group.rules:
            if r['from_port'] == from_port\
            and r['to_port'] == to_port\
            and r['ip_protocol'] == ip_protocol:
                return True
        return False

    def get_usergroup(self, username):
        return self.get_tenant(username)

    def delete_usergroup(self, username, deleteUser=True):
        try:
            self.delete_tenant_member(username, username, True)
        except ClientException:
            logger.warn('Could not remove admin role from username %s' %
                        username)<commit_msg>Updates to address openstack's changes to security groups and rules. 	modified:   service/drivers/openstackUserManager.py<commit_after>import os

from keystoneclient.exceptions import NotFound, ClientException
from keystoneclient.v3 import client as ks_client
from novaclient.v1_1 import client as nova_client

from atmosphere.logger import logger
from atmosphere import settings

"""
OpenStack CloudAdmin Libarary
    Use this library to:
    * manage users within Keystone - openstack auth
"""


class UserManager():
    keystone = None
    nova = None
    user = None
    password = <PASSWORD>
    tenant = None

    @classmethod
    def settings_init(self, *args, **kwargs):
        settings_args = {
            'username': settings.OPENSTACK_ADMIN_KEY,
            'password': settings.OPENSTACK_ADMIN_SECRET,
            'tenant_name': settings.OPENSTACK_ADMIN_TENANT,
            'auth_url': settings.OPENSTACK_ADMIN_URL,
            'region_name': settings.OPENSTACK_DEFAULT_REGION
        }
        settings_args.update(kwargs)
        manager = UserManager(*args, **settings_args)
        return manager

    @classmethod
    def lc_driver_init(self, lc_driver, region=None, *args, **kwargs):
        if not region:
            region = settings.OPENSTACK_DEFAULT_REGION
        lc_driver_args = {
            'username': lc_driver.key,
            'password': <PASSWORD>,
            'tenant_name': lc_driver._ex_tenant_name,
            'auth_url': lc_driver._ex_force_auth_url,
            'region_name': region
        }
        lc_driver_args.update(kwargs)
        manager = UserManager(*args, **lc_driver_args)
        return manager

    def __init__(self, *args, **kwargs):
        self.newConnection(*args, **kwargs)

    def newConnection(self, *args, **kwargs):
        self.keystone = ks_client.Client(*args, **kwargs)
        self.nova = nova_client.Client(kwargs.pop('username'),
                                       kwargs.pop('password'),
                                       kwargs.pop('tenant_name'),
                                       kwargs.pop('auth_url'),
                                       kwargs.pop('region_name'),
                                       *args, no_cache=True, **kwargs)
        self.nova.client.region_name = settings.OPENSTACK_DEFAULT_REGION

    ##Composite Classes##
    def add_usergroup(self, username, password,
                     createUser=True, adminRole=False):
        """
        Create a group for this user only
        then create the user
        """
        #Create tenant for user/group
        tenant = self.add_tenant(username)

        #Create user
        try:
            user = self.add_user(username, password, tenant.name)
        except ClientException as user_exists:
            logger.debug('Received Error %s on add, User exists.' %
                         user_exists)
            user = self.get_user(username)

        logger.debug("Assign Tenant:%s Member:%s Role:%s" %
                    (username, username, adminRole))
        try:
            role = self.add_tenant_member(username, username, adminRole)
        except ClientException:
            logger.warn('Could not assign role to username %s' % username)
        try:
            # keystone admin always gets access, always has admin priv.
            self.add_tenant_member(username, self.keystone.username, True)
        except ClientException:
            logger.warn('Could not assign admin role to username %s' %
                        self.keystone.username)
        return (tenant, user, role)

    def add_security_group_rule(self, nova, protocol, security_group):
        """
        Add a security group rule if it doesn't already exist.
        """
        (ip_protocol, from_port, to_port) = protocol
        if not self.find_rule(security_group, ip_protocol,
                          from_port, to_port):
            nova.security_group_rules.create(security_group.id,
                                             ip_protocol=ip_protocol,
                                             from_port=from_port,
                                             to_port=to_port)
        return True

    def build_security_group(self, username, password, tenant_name,
                             protocol_list=None, *args, **kwargs):
        nova = nova_client.Client(username,
                                  password,
                                  tenant_name,
                                  self.nova.client.auth_url,
                                  self.nova.client.region_name,
                                  *args, no_cache=True, **kwargs)
        nova.client.region_name = self.nova.client.region_name
        if not protocol_list:
            #Build a "good" one.
            protocol_list = [
                ('TCP', 22, 22),
                ('TCP', 80, 80),
                ('TCP', 5666, 5666),
                ('TCP', 5900, 5904),
                ('TCP', 4200, 4200),
                ('ICMP', -1, -1),
            ]
        default_sec_group = nova.security_groups.find(name='default')
        for protocol in protocol_list:
            self.add_security_group(nova, protocol, default_sec_group)
        return nova.security_groups.find(name='default')

    def find_rule(self, security_group, ip_protocol, from_port, to_port):
        for r in security_group.rules:
            if r['from_port'] == from_port\
            and r['to_port'] == to_port\
            and r['ip_protocol'] == ip_protocol:
                return True
        return False

    def get_usergroup(self, username):
        return self.get_tenant(username)

    def delete_usergroup(self, username, deleteUser=True):
        try:
            self.delete_tenant_member(username, username, True)
        except ClientException:
            logger.warn('Could not remove admin role from username %s' %
                        username)
{'fraction_non_alphanumeric': 0.08900295806507744, 'fraction_numerical': 0.006438141639116061, 'mean_word_length': 1.797517644195668, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4612491', 'n_tokens_mistral': 3137, 'n_tokens_neox': 3018, 'n_words': 706}