idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
244,300 | def relation_set ( relation_id = None , relation_settings = None , * * kwargs ) : try : if relation_id in relation_ids ( 'cluster' ) : return leader_set ( settings = relation_settings , * * kwargs ) else : raise NotImplementedError except NotImplementedError : return _relation_set ( relation_id = relation_id , relation_settings = relation_settings , * * kwargs ) | Attempt to use leader - set if supported in the current version of Juju otherwise falls back on relation - set . | 101 | 23 |
244,301 | def relation_get ( attribute = None , unit = None , rid = None ) : try : if rid in relation_ids ( 'cluster' ) : return leader_get ( attribute , rid ) else : raise NotImplementedError except NotImplementedError : return _relation_get ( attribute = attribute , rid = rid , unit = unit ) | Attempt to use leader - get if supported in the current version of Juju otherwise falls back on relation - get . | 75 | 23 |
244,302 | def peer_retrieve ( key , relation_name = 'cluster' ) : cluster_rels = relation_ids ( relation_name ) if len ( cluster_rels ) > 0 : cluster_rid = cluster_rels [ 0 ] return relation_get ( attribute = key , rid = cluster_rid , unit = local_unit ( ) ) else : raise ValueError ( 'Unable to detect' 'peer relation {}' . format ( relation_name ) ) | Retrieve a named key from peer relation relation_name . | 101 | 12 |
244,303 | def peer_echo ( includes = None , force = False ) : try : is_leader ( ) except NotImplementedError : pass else : if not force : return # NOOP if leader-election is supported # Use original non-leader calls relation_get = _relation_get relation_set = _relation_set rdata = relation_get ( ) echo_data = { } if includes is None : echo_data = rdata . copy ( ) for ex in [ 'private-address' , 'public-address' ] : if ex in echo_data : echo_data . pop ( ex ) else : for attribute , value in six . iteritems ( rdata ) : for include in includes : if include in attribute : echo_data [ attribute ] = value if len ( echo_data ) > 0 : relation_set ( relation_settings = echo_data ) | Echo filtered attributes back onto the same relation for storage . | 185 | 12 |
244,304 | def peer_store_and_set ( relation_id = None , peer_relation_name = 'cluster' , peer_store_fatal = False , relation_settings = None , delimiter = '_' , * * kwargs ) : relation_settings = relation_settings if relation_settings else { } relation_set ( relation_id = relation_id , relation_settings = relation_settings , * * kwargs ) if is_relation_made ( peer_relation_name ) : for key , value in six . iteritems ( dict ( list ( kwargs . items ( ) ) + list ( relation_settings . items ( ) ) ) ) : key_prefix = relation_id or current_relation_id ( ) peer_store ( key_prefix + delimiter + key , value , relation_name = peer_relation_name ) else : if peer_store_fatal : raise ValueError ( 'Unable to detect ' 'peer relation {}' . format ( peer_relation_name ) ) | Store passed - in arguments both in argument relation and in peer storage . | 220 | 14 |
244,305 | def sed ( filename , before , after , flags = 'g' ) : expression = r's/{0}/{1}/{2}' . format ( before , after , flags ) return subprocess . check_call ( [ "sed" , "-i" , "-r" , "-e" , expression , os . path . expanduser ( filename ) ] ) | Search and replaces the given pattern on filename . | 80 | 9 |
244,306 | def get_listening ( self , listen = [ '0.0.0.0' ] ) : if listen == [ '0.0.0.0' ] : return listen value = [ ] for network in listen : try : ip = get_address_in_network ( network = network , fatal = True ) except ValueError : if is_ip ( network ) : ip = network else : try : ip = get_iface_addr ( iface = network , fatal = False ) [ 0 ] except IndexError : continue value . append ( ip ) if value == [ ] : return [ '0.0.0.0' ] return value | Returns a list of addresses SSH can list on | 140 | 9 |
244,307 | def get_loader ( templates_dir , os_release ) : tmpl_dirs = [ ( rel , os . path . join ( templates_dir , rel ) ) for rel in six . itervalues ( OPENSTACK_CODENAMES ) ] if not os . path . isdir ( templates_dir ) : log ( 'Templates directory not found @ %s.' % templates_dir , level = ERROR ) raise OSConfigException # the bottom contains tempaltes_dir and possibly a common templates dir # shipped with the helper. loaders = [ FileSystemLoader ( templates_dir ) ] helper_templates = os . path . join ( os . path . dirname ( __file__ ) , 'templates' ) if os . path . isdir ( helper_templates ) : loaders . append ( FileSystemLoader ( helper_templates ) ) for rel , tmpl_dir in tmpl_dirs : if os . path . isdir ( tmpl_dir ) : loaders . insert ( 0 , FileSystemLoader ( tmpl_dir ) ) if rel == os_release : break # demote this log to the lowest level; we don't really need to see these # lots in production even when debugging. log ( 'Creating choice loader with dirs: %s' % [ l . searchpath for l in loaders ] , level = TRACE ) return ChoiceLoader ( loaders ) | Create a jinja2 . ChoiceLoader containing template dirs up to and including os_release . If directory template directory is missing at templates_dir it will be omitted from the loader . templates_dir is added to the bottom of the search list as a base loading dir . | 309 | 57 |
244,308 | def complete_contexts ( self ) : if self . _complete_contexts : return self . _complete_contexts self . context ( ) return self . _complete_contexts | Return a list of interfaces that have satisfied contexts . | 39 | 10 |
244,309 | def write ( self , config_file ) : if config_file not in self . templates : log ( 'Config not registered: %s' % config_file , level = ERROR ) raise OSConfigException _out = self . render ( config_file ) if six . PY3 : _out = _out . encode ( 'UTF-8' ) with open ( config_file , 'wb' ) as out : out . write ( _out ) log ( 'Wrote template %s.' % config_file , level = INFO ) | Write a single config file raises if config file is not registered . | 114 | 13 |
244,310 | def write_all ( self ) : [ self . write ( k ) for k in six . iterkeys ( self . templates ) ] | Write out all registered config files . | 28 | 7 |
244,311 | def set_release ( self , openstack_release ) : self . _tmpl_env = None self . openstack_release = openstack_release self . _get_tmpl_env ( ) | Resets the template environment and generates a new template loader based on a the new openstack release . | 44 | 20 |
244,312 | def complete_contexts ( self ) : interfaces = [ ] [ interfaces . extend ( i . complete_contexts ( ) ) for i in six . itervalues ( self . templates ) ] return interfaces | Returns a list of context interfaces that yield a complete context . | 44 | 12 |
244,313 | def is_elected_leader ( resource ) : try : return juju_is_leader ( ) except NotImplementedError : log ( 'Juju leadership election feature not enabled' ', using fallback support' , level = WARNING ) if is_clustered ( ) : if not is_crm_leader ( resource ) : log ( 'Deferring action to CRM leader.' , level = INFO ) return False else : peers = peer_units ( ) if peers and not oldest_peer ( peers ) : log ( 'Deferring action to oldest service unit.' , level = INFO ) return False return True | Returns True if the charm executing this is the elected cluster leader . | 131 | 13 |
244,314 | def is_crm_dc ( ) : cmd = [ 'crm' , 'status' ] try : status = subprocess . check_output ( cmd , stderr = subprocess . STDOUT ) if not isinstance ( status , six . text_type ) : status = six . text_type ( status , "utf-8" ) except subprocess . CalledProcessError as ex : raise CRMDCNotFound ( str ( ex ) ) current_dc = '' for line in status . split ( '\n' ) : if line . startswith ( 'Current DC' ) : # Current DC: juju-lytrusty-machine-2 (168108163) - partition with quorum current_dc = line . split ( ':' ) [ 1 ] . split ( ) [ 0 ] if current_dc == get_unit_hostname ( ) : return True elif current_dc == 'NONE' : raise CRMDCNotFound ( 'Current DC: NONE' ) return False | Determine leadership by querying the pacemaker Designated Controller | 217 | 13 |
244,315 | def is_crm_leader ( resource , retry = False ) : if resource == DC_RESOURCE_NAME : return is_crm_dc ( ) cmd = [ 'crm' , 'resource' , 'show' , resource ] try : status = subprocess . check_output ( cmd , stderr = subprocess . STDOUT ) if not isinstance ( status , six . text_type ) : status = six . text_type ( status , "utf-8" ) except subprocess . CalledProcessError : status = None if status and get_unit_hostname ( ) in status : return True if status and "resource %s is NOT running" % ( resource ) in status : raise CRMResourceNotFound ( "CRM resource %s not found" % ( resource ) ) return False | Returns True if the charm calling this is the elected corosync leader as returned by calling the external crm command . | 174 | 24 |
244,316 | def peer_ips ( peer_relation = 'cluster' , addr_key = 'private-address' ) : peers = { } for r_id in relation_ids ( peer_relation ) : for unit in relation_list ( r_id ) : peers [ unit ] = relation_get ( addr_key , rid = r_id , unit = unit ) return peers | Return a dict of peers and their private - address | 80 | 10 |
244,317 | def oldest_peer ( peers ) : local_unit_no = int ( os . getenv ( 'JUJU_UNIT_NAME' ) . split ( '/' ) [ 1 ] ) for peer in peers : remote_unit_no = int ( peer . split ( '/' ) [ 1 ] ) if remote_unit_no < local_unit_no : return False return True | Determines who the oldest peer is by comparing unit numbers . | 84 | 13 |
244,318 | def canonical_url ( configs , vip_setting = 'vip' ) : scheme = 'http' if 'https' in configs . complete_contexts ( ) : scheme = 'https' if is_clustered ( ) : addr = config_get ( vip_setting ) else : addr = unit_get ( 'private-address' ) return '%s://%s' % ( scheme , addr ) | Returns the correct HTTP URL to this host given the state of HTTPS configuration and hacluster . | 92 | 19 |
244,319 | def distributed_wait ( modulo = None , wait = None , operation_name = 'operation' ) : if modulo is None : modulo = config_get ( 'modulo-nodes' ) or 3 if wait is None : wait = config_get ( 'known-wait' ) or 30 if juju_is_leader ( ) : # The leader should never wait calculated_wait = 0 else : # non_zero_wait=True guarantees the non-leader who gets modulo 0 # will still wait calculated_wait = modulo_distribution ( modulo = modulo , wait = wait , non_zero_wait = True ) msg = "Waiting {} seconds for {} ..." . format ( calculated_wait , operation_name ) log ( msg , DEBUG ) status_set ( 'maintenance' , msg ) time . sleep ( calculated_wait ) | Distribute operations by waiting based on modulo_distribution | 184 | 12 |
244,320 | def update ( fatal = False ) : cmd = [ 'yum' , '--assumeyes' , 'update' ] log ( "Update with fatal: {}" . format ( fatal ) ) _run_yum_command ( cmd , fatal ) | Update local yum cache . | 54 | 6 |
244,321 | def yum_search ( packages ) : output = { } cmd = [ 'yum' , 'search' ] if isinstance ( packages , six . string_types ) : cmd . append ( packages ) else : cmd . extend ( packages ) log ( "Searching for {}" . format ( packages ) ) result = subprocess . check_output ( cmd ) for package in list ( packages ) : output [ package ] = package in result return output | Search for a package . | 95 | 5 |
244,322 | def _run_yum_command ( cmd , fatal = False ) : env = os . environ . copy ( ) if fatal : retry_count = 0 result = None # If the command is considered "fatal", we need to retry if the yum # lock was not acquired. while result is None or result == YUM_NO_LOCK : try : result = subprocess . check_call ( cmd , env = env ) except subprocess . CalledProcessError as e : retry_count = retry_count + 1 if retry_count > YUM_NO_LOCK_RETRY_COUNT : raise result = e . returncode log ( "Couldn't acquire YUM lock. Will retry in {} seconds." "" . format ( YUM_NO_LOCK_RETRY_DELAY ) ) time . sleep ( YUM_NO_LOCK_RETRY_DELAY ) else : subprocess . call ( cmd , env = env ) | Run an YUM command . | 209 | 6 |
244,323 | def py ( self , output ) : import pprint pprint . pprint ( output , stream = self . outfile ) | Output data as a nicely - formatted python data structure | 26 | 10 |
244,324 | def csv ( self , output ) : import csv csvwriter = csv . writer ( self . outfile ) csvwriter . writerows ( output ) | Output data as excel - compatible CSV | 35 | 7 |
244,325 | def tab ( self , output ) : import csv csvwriter = csv . writer ( self . outfile , dialect = csv . excel_tab ) csvwriter . writerows ( output ) | Output data in excel - compatible tab - delimited format | 43 | 11 |
244,326 | def subcommand ( self , command_name = None ) : def wrapper ( decorated ) : cmd_name = command_name or decorated . __name__ subparser = self . subparsers . add_parser ( cmd_name , description = decorated . __doc__ ) for args , kwargs in describe_arguments ( decorated ) : subparser . add_argument ( * args , * * kwargs ) subparser . set_defaults ( func = decorated ) return decorated return wrapper | Decorate a function as a subcommand . Use its arguments as the command - line arguments | 104 | 18 |
244,327 | def run ( self ) : arguments = self . argument_parser . parse_args ( ) argspec = inspect . getargspec ( arguments . func ) vargs = [ ] for arg in argspec . args : vargs . append ( getattr ( arguments , arg ) ) if argspec . varargs : vargs . extend ( getattr ( arguments , argspec . varargs ) ) output = arguments . func ( * vargs ) if getattr ( arguments . func , '_cli_test_command' , False ) : self . exit_code = 0 if output else 1 output = '' if getattr ( arguments . func , '_cli_no_output' , False ) : output = '' self . formatter . format_output ( output , arguments . format ) if charmhelpers . core . unitdata . _KV : charmhelpers . core . unitdata . _KV . flush ( ) | Run cli processing arguments and executing subcommands . | 194 | 11 |
244,328 | def ssh_authorized_peers ( peer_interface , user , group = None , ensure_local_user = False ) : if ensure_local_user : ensure_user ( user , group ) priv_key , pub_key = get_keypair ( user ) hook = hook_name ( ) if hook == '%s-relation-joined' % peer_interface : relation_set ( ssh_pub_key = pub_key ) elif hook == '%s-relation-changed' % peer_interface or hook == '%s-relation-departed' % peer_interface : hosts = [ ] keys = [ ] for r_id in relation_ids ( peer_interface ) : for unit in related_units ( r_id ) : ssh_pub_key = relation_get ( 'ssh_pub_key' , rid = r_id , unit = unit ) priv_addr = relation_get ( 'private-address' , rid = r_id , unit = unit ) if ssh_pub_key : keys . append ( ssh_pub_key ) hosts . append ( priv_addr ) else : log ( 'ssh_authorized_peers(): ssh_pub_key ' 'missing for unit %s, skipping.' % unit ) write_authorized_keys ( user , keys ) write_known_hosts ( user , hosts ) authed_hosts = ':' . join ( hosts ) relation_set ( ssh_authorized_hosts = authed_hosts ) | Main setup function should be called from both peer - changed and - joined hooks with the same parameters . | 319 | 20 |
244,329 | def collect_authed_hosts ( peer_interface ) : hosts = [ ] for r_id in ( relation_ids ( peer_interface ) or [ ] ) : for unit in related_units ( r_id ) : private_addr = relation_get ( 'private-address' , rid = r_id , unit = unit ) authed_hosts = relation_get ( 'ssh_authorized_hosts' , rid = r_id , unit = unit ) if not authed_hosts : log ( 'Peer %s has not authorized *any* hosts yet, skipping.' % ( unit ) , level = INFO ) continue if unit_private_ip ( ) in authed_hosts . split ( ':' ) : hosts . append ( private_addr ) else : log ( 'Peer %s has not authorized *this* host yet, skipping.' % ( unit ) , level = INFO ) return hosts | Iterate through the units on peer interface to find all that have the calling host in its authorized hosts list | 198 | 21 |
244,330 | def sync_path_to_host ( path , host , user , verbose = False , cmd = None , gid = None , fatal = False ) : cmd = cmd or copy ( BASE_CMD ) if not verbose : cmd . append ( '-silent' ) # removing trailing slash from directory paths, unison # doesn't like these. if path . endswith ( '/' ) : path = path [ : ( len ( path ) - 1 ) ] cmd = cmd + [ path , 'ssh://%s@%s/%s' % ( user , host , path ) ] try : log ( 'Syncing local path %s to %s@%s:%s' % ( path , user , host , path ) ) run_as_user ( user , cmd , gid ) except Exception : log ( 'Error syncing remote files' ) if fatal : raise | Sync path to an specific peer host | 190 | 7 |
244,331 | def sync_to_peer ( host , user , paths = None , verbose = False , cmd = None , gid = None , fatal = False ) : if paths : for p in paths : sync_path_to_host ( p , host , user , verbose , cmd , gid , fatal ) | Sync paths to an specific peer host | 66 | 7 |
244,332 | def sync_to_peers ( peer_interface , user , paths = None , verbose = False , cmd = None , gid = None , fatal = False ) : if paths : for host in collect_authed_hosts ( peer_interface ) : sync_to_peer ( host , user , paths , verbose , cmd , gid , fatal ) | Sync all hosts to an specific path | 78 | 7 |
244,333 | def parse_options ( given , available ) : for key , value in sorted ( given . items ( ) ) : if not value : continue if key in available : yield "--{0}={1}" . format ( key , value ) | Given a set of options check if available | 50 | 8 |
244,334 | def pip_install_requirements ( requirements , constraints = None , * * options ) : command = [ "install" ] available_options = ( 'proxy' , 'src' , 'log' , ) for option in parse_options ( options , available_options ) : command . append ( option ) command . append ( "-r {0}" . format ( requirements ) ) if constraints : command . append ( "-c {0}" . format ( constraints ) ) log ( "Installing from file: {} with constraints {} " "and options: {}" . format ( requirements , constraints , command ) ) else : log ( "Installing from file: {} with options: {}" . format ( requirements , command ) ) pip_execute ( command ) | Install a requirements file . | 156 | 5 |
244,335 | def pip_install ( package , fatal = False , upgrade = False , venv = None , constraints = None , * * options ) : if venv : venv_python = os . path . join ( venv , 'bin/pip' ) command = [ venv_python , "install" ] else : command = [ "install" ] available_options = ( 'proxy' , 'src' , 'log' , 'index-url' , ) for option in parse_options ( options , available_options ) : command . append ( option ) if upgrade : command . append ( '--upgrade' ) if constraints : command . extend ( [ '-c' , constraints ] ) if isinstance ( package , list ) : command . extend ( package ) else : command . append ( package ) log ( "Installing {} package with options: {}" . format ( package , command ) ) if venv : subprocess . check_call ( command ) else : pip_execute ( command ) | Install a python package | 212 | 4 |
244,336 | def pip_uninstall ( package , * * options ) : command = [ "uninstall" , "-q" , "-y" ] available_options = ( 'proxy' , 'log' , ) for option in parse_options ( options , available_options ) : command . append ( option ) if isinstance ( package , list ) : command . extend ( package ) else : command . append ( package ) log ( "Uninstalling {} package with options: {}" . format ( package , command ) ) pip_execute ( command ) | Uninstall a python package | 113 | 5 |
244,337 | def pip_create_virtualenv ( path = None ) : if six . PY2 : apt_install ( 'python-virtualenv' ) else : apt_install ( 'python3-virtualenv' ) if path : venv_path = path else : venv_path = os . path . join ( charm_dir ( ) , 'venv' ) if not os . path . exists ( venv_path ) : subprocess . check_call ( [ 'virtualenv' , venv_path ] ) | Create an isolated Python environment . | 111 | 6 |
244,338 | def configure_sources ( update = False , sources_var = 'install_sources' , keys_var = 'install_keys' ) : sources = safe_load ( ( config ( sources_var ) or '' ) . strip ( ) ) or [ ] keys = safe_load ( ( config ( keys_var ) or '' ) . strip ( ) ) or None if isinstance ( sources , six . string_types ) : sources = [ sources ] if keys is None : for source in sources : add_source ( source , None ) else : if isinstance ( keys , six . string_types ) : keys = [ keys ] if len ( sources ) != len ( keys ) : raise SourceConfigError ( 'Install sources and keys lists are different lengths' ) for source , key in zip ( sources , keys ) : add_source ( source , key ) if update : _fetch_update ( fatal = True ) | Configure multiple sources from charm configuration . | 195 | 8 |
244,339 | def install_remote ( source , * args , * * kwargs ) : # We ONLY check for True here because can_handle may return a string # explaining why it can't handle a given source. handlers = [ h for h in plugins ( ) if h . can_handle ( source ) is True ] for handler in handlers : try : return handler . install ( source , * args , * * kwargs ) except UnhandledSource as e : log ( 'Install source attempt unsuccessful: {}' . format ( e ) , level = 'WARNING' ) raise UnhandledSource ( "No handler found for source {}" . format ( source ) ) | Install a file tree from a remote source . | 136 | 9 |
244,340 | def base_url ( self , url ) : parts = list ( self . parse_url ( url ) ) parts [ 4 : ] = [ '' for i in parts [ 4 : ] ] return urlunparse ( parts ) | Return url without querystring or fragment | 47 | 7 |
244,341 | def is_block_device ( path ) : if not os . path . exists ( path ) : return False return S_ISBLK ( os . stat ( path ) . st_mode ) | Confirm device at path is a valid block device node . | 41 | 12 |
244,342 | def zap_disk ( block_device ) : # https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b # sometimes sgdisk exits non-zero; this is OK, dd will clean up call ( [ 'sgdisk' , '--zap-all' , '--' , block_device ] ) call ( [ 'sgdisk' , '--clear' , '--mbrtogpt' , '--' , block_device ] ) dev_end = check_output ( [ 'blockdev' , '--getsz' , block_device ] ) . decode ( 'UTF-8' ) gpt_end = int ( dev_end . split ( ) [ 0 ] ) - 100 check_call ( [ 'dd' , 'if=/dev/zero' , 'of=%s' % ( block_device ) , 'bs=1M' , 'count=1' ] ) check_call ( [ 'dd' , 'if=/dev/zero' , 'of=%s' % ( block_device ) , 'bs=512' , 'count=100' , 'seek=%s' % ( gpt_end ) ] ) | Clear a block device of partition table . Relies on sgdisk which is installed as pat of the gdisk package in Ubuntu . | 282 | 27 |
244,343 | def is_device_mounted ( device ) : try : out = check_output ( [ 'lsblk' , '-P' , device ] ) . decode ( 'UTF-8' ) except Exception : return False return bool ( re . search ( r'MOUNTPOINT=".+"' , out ) ) | Given a device path return True if that device is mounted and False if it isn t . | 69 | 18 |
244,344 | def mkfs_xfs ( device , force = False ) : cmd = [ 'mkfs.xfs' ] if force : cmd . append ( "-f" ) cmd += [ '-i' , 'size=1024' , device ] check_call ( cmd ) | Format device with XFS filesystem . | 58 | 7 |
244,345 | def wait_for_machine ( num_machines = 1 , timeout = 300 ) : # You may think this is a hack, and you'd be right. The easiest way # to tell what environment we're working in (LXC vs EC2) is to check # the dns-name of the first machine. If it's localhost we're in LXC # and we can just return here. if get_machine_data ( ) [ 0 ] [ 'dns-name' ] == 'localhost' : return 1 , 0 start_time = time . time ( ) while True : # Drop the first machine, since it's the Zookeeper and that's # not a machine that we need to wait for. This will only work # for EC2 environments, which is why we return early above if # we're in LXC. machine_data = get_machine_data ( ) non_zookeeper_machines = [ machine_data [ key ] for key in list ( machine_data . keys ( ) ) [ 1 : ] ] if len ( non_zookeeper_machines ) >= num_machines : all_machines_running = True for machine in non_zookeeper_machines : if machine . get ( 'instance-state' ) != 'running' : all_machines_running = False break if all_machines_running : break if time . time ( ) - start_time >= timeout : raise RuntimeError ( 'timeout waiting for service to start' ) time . sleep ( SLEEP_AMOUNT ) return num_machines , time . time ( ) - start_time | Wait timeout seconds for num_machines machines to come up . | 356 | 14 |
244,346 | def wait_for_unit ( service_name , timeout = 480 ) : wait_for_machine ( num_machines = 1 ) start_time = time . time ( ) while True : state = unit_info ( service_name , 'agent-state' ) if 'error' in state or state == 'started' : break if time . time ( ) - start_time >= timeout : raise RuntimeError ( 'timeout waiting for service to start' ) time . sleep ( SLEEP_AMOUNT ) if state != 'started' : raise RuntimeError ( 'unit did not start, agent-state: ' + state ) | Wait timeout seconds for a given service name to come up . | 134 | 12 |
244,347 | def wait_for_relation ( service_name , relation_name , timeout = 120 ) : start_time = time . time ( ) while True : relation = unit_info ( service_name , 'relations' ) . get ( relation_name ) if relation is not None and relation [ 'state' ] == 'up' : break if time . time ( ) - start_time >= timeout : raise RuntimeError ( 'timeout waiting for relation to be up' ) time . sleep ( SLEEP_AMOUNT ) | Wait timeout seconds for a given relation to come up . | 109 | 11 |
244,348 | def service_available ( service_name ) : try : subprocess . check_output ( [ 'service' , service_name , 'status' ] , stderr = subprocess . STDOUT ) . decode ( 'UTF-8' ) except subprocess . CalledProcessError as e : return b'unrecognized service' not in e . output else : return True | Determine whether a system service is available | 79 | 9 |
244,349 | def install_salt_support ( from_ppa = True ) : if from_ppa : subprocess . check_call ( [ '/usr/bin/add-apt-repository' , '--yes' , 'ppa:saltstack/salt' , ] ) subprocess . check_call ( [ '/usr/bin/apt-get' , 'update' ] ) # We install salt-common as salt-minion would run the salt-minion # daemon. charmhelpers . fetch . apt_install ( 'salt-common' ) | Installs the salt - minion helper for machine state . | 121 | 11 |
244,350 | def update_machine_state ( state_path ) : charmhelpers . contrib . templating . contexts . juju_state_to_yaml ( salt_grains_path ) subprocess . check_call ( [ 'salt-call' , '--local' , 'state.template' , state_path , ] ) | Update the machine state using the provided state declaration . | 74 | 10 |
244,351 | def pool_exists ( service , name ) : try : out = check_output ( [ 'rados' , '--id' , service , 'lspools' ] ) if six . PY3 : out = out . decode ( 'UTF-8' ) except CalledProcessError : return False return name in out . split ( ) | Check to see if a RADOS pool already exists . | 73 | 11 |
244,352 | def install ( ) : ceph_dir = "/etc/ceph" if not os . path . exists ( ceph_dir ) : os . mkdir ( ceph_dir ) apt_install ( 'ceph-common' , fatal = True ) | Basic Ceph client installation . | 55 | 6 |
244,353 | def rbd_exists ( service , pool , rbd_img ) : try : out = check_output ( [ 'rbd' , 'list' , '--id' , service , '--pool' , pool ] ) if six . PY3 : out = out . decode ( 'UTF-8' ) except CalledProcessError : return False return rbd_img in out | Check to see if a RADOS block device exists . | 83 | 11 |
244,354 | def create_rbd_image ( service , pool , image , sizemb ) : cmd = [ 'rbd' , 'create' , image , '--size' , str ( sizemb ) , '--id' , service , '--pool' , pool ] check_call ( cmd ) | Create a new RADOS block device . | 65 | 8 |
244,355 | def set_app_name_for_pool ( client , pool , name ) : if cmp_pkgrevno ( 'ceph-common' , '12.0.0' ) >= 0 : cmd = [ 'ceph' , '--id' , client , 'osd' , 'pool' , 'application' , 'enable' , pool , name ] check_call ( cmd ) | Calls osd pool application enable for the specified pool name | 86 | 12 |
244,356 | def create_pool ( service , name , replicas = 3 , pg_num = None ) : if pool_exists ( service , name ) : log ( "Ceph pool {} already exists, skipping creation" . format ( name ) , level = WARNING ) return if not pg_num : # Calculate the number of placement groups based # on upstream recommended best practices. osds = get_osds ( service ) if osds : pg_num = ( len ( osds ) * 100 // replicas ) else : # NOTE(james-page): Default to 200 for older ceph versions # which don't support OSD query from cli pg_num = 200 cmd = [ 'ceph' , '--id' , service , 'osd' , 'pool' , 'create' , name , str ( pg_num ) ] check_call ( cmd ) update_pool ( service , name , settings = { 'size' : str ( replicas ) } ) | Create a new RADOS pool . | 207 | 7 |
244,357 | def add_key ( service , key ) : keyring = _keyring_path ( service ) if os . path . exists ( keyring ) : with open ( keyring , 'r' ) as ring : if key in ring . read ( ) : log ( 'Ceph keyring exists at %s and has not changed.' % keyring , level = DEBUG ) return log ( 'Updating existing keyring %s.' % keyring , level = DEBUG ) cmd = [ 'ceph-authtool' , keyring , '--create-keyring' , '--name=client.{}' . format ( service ) , '--add-key={}' . format ( key ) ] check_call ( cmd ) log ( 'Created new ceph keyring at %s.' % keyring , level = DEBUG ) | Add a key to a keyring . | 176 | 8 |
244,358 | def delete_keyring ( service ) : keyring = _keyring_path ( service ) if not os . path . exists ( keyring ) : log ( 'Keyring does not exist at %s' % keyring , level = WARNING ) return os . remove ( keyring ) log ( 'Deleted ring at %s.' % keyring , level = INFO ) | Delete an existing Ceph keyring . | 78 | 8 |
244,359 | def create_key_file ( service , key ) : keyfile = _keyfile_path ( service ) if os . path . exists ( keyfile ) : log ( 'Keyfile exists at %s.' % keyfile , level = WARNING ) return with open ( keyfile , 'w' ) as fd : fd . write ( key ) log ( 'Created new keyfile at %s.' % keyfile , level = INFO ) | Create a file containing key . | 93 | 6 |
244,360 | def get_ceph_nodes ( relation = 'ceph' ) : hosts = [ ] for r_id in relation_ids ( relation ) : for unit in related_units ( r_id ) : hosts . append ( relation_get ( 'private-address' , unit = unit , rid = r_id ) ) return hosts | Query named relation to determine current nodes . | 72 | 8 |
244,361 | def configure ( service , key , auth , use_syslog ) : add_key ( service , key ) create_key_file ( service , key ) hosts = get_ceph_nodes ( ) with open ( '/etc/ceph/ceph.conf' , 'w' ) as ceph_conf : ceph_conf . write ( CEPH_CONF . format ( auth = auth , keyring = _keyring_path ( service ) , mon_hosts = "," . join ( map ( str , hosts ) ) , use_syslog = use_syslog ) ) modprobe ( 'rbd' ) | Perform basic configuration of Ceph . | 139 | 8 |
244,362 | def image_mapped ( name ) : try : out = check_output ( [ 'rbd' , 'showmapped' ] ) if six . PY3 : out = out . decode ( 'UTF-8' ) except CalledProcessError : return False return name in out | Determine whether a RADOS block device is mapped locally . | 60 | 13 |
244,363 | def map_block_storage ( service , pool , image ) : cmd = [ 'rbd' , 'map' , '{}/{}' . format ( pool , image ) , '--user' , service , '--secret' , _keyfile_path ( service ) , ] check_call ( cmd ) | Map a RADOS block device for local use . | 69 | 10 |
244,364 | def make_filesystem ( blk_device , fstype = 'ext4' , timeout = 10 ) : count = 0 e_noent = os . errno . ENOENT while not os . path . exists ( blk_device ) : if count >= timeout : log ( 'Gave up waiting on block device %s' % blk_device , level = ERROR ) raise IOError ( e_noent , os . strerror ( e_noent ) , blk_device ) log ( 'Waiting for block device %s to appear' % blk_device , level = DEBUG ) count += 1 time . sleep ( 1 ) else : log ( 'Formatting block device %s as filesystem %s.' % ( blk_device , fstype ) , level = INFO ) check_call ( [ 'mkfs' , '-t' , fstype , blk_device ] ) | Make a new filesystem on the specified block device . | 198 | 10 |
244,365 | def place_data_on_block_device ( blk_device , data_src_dst ) : # mount block device into /mnt mount ( blk_device , '/mnt' ) # copy data to /mnt copy_files ( data_src_dst , '/mnt' ) # umount block device umount ( '/mnt' ) # Grab user/group ID's from original source _dir = os . stat ( data_src_dst ) uid = _dir . st_uid gid = _dir . st_gid # re-mount where the data should originally be # TODO: persist is currently a NO-OP in core.host mount ( blk_device , data_src_dst , persist = True ) # ensure original ownership of new mount. os . chown ( data_src_dst , uid , gid ) | Migrate data in data_src_dst to blk_device and then remount . | 192 | 20 |
244,366 | def ensure_ceph_keyring ( service , user = None , group = None , relation = 'ceph' , key = None ) : if not key : for rid in relation_ids ( relation ) : for unit in related_units ( rid ) : key = relation_get ( 'key' , rid = rid , unit = unit ) if key : break if not key : return False add_key ( service = service , key = key ) keyring = _keyring_path ( service ) if user and group : check_call ( [ 'chown' , '%s.%s' % ( user , group ) , keyring ] ) return True | Ensures a ceph keyring is created for a named service and optionally ensures user and group ownership . | 141 | 22 |
244,367 | def get_previous_request ( rid ) : request = None broker_req = relation_get ( attribute = 'broker_req' , rid = rid , unit = local_unit ( ) ) if broker_req : request_data = json . loads ( broker_req ) request = CephBrokerRq ( api_version = request_data [ 'api-version' ] , request_id = request_data [ 'request-id' ] ) request . set_ops ( request_data [ 'ops' ] ) return request | Return the last ceph broker request sent on a given relation | 116 | 12 |
244,368 | def get_request_states ( request , relation = 'ceph' ) : complete = [ ] requests = { } for rid in relation_ids ( relation ) : complete = False previous_request = get_previous_request ( rid ) if request == previous_request : sent = True complete = is_request_complete_for_rid ( previous_request , rid ) else : sent = False complete = False requests [ rid ] = { 'sent' : sent , 'complete' : complete , } return requests | Return a dict of requests per relation id with their corresponding completion state . | 108 | 14 |
244,369 | def is_request_sent ( request , relation = 'ceph' ) : states = get_request_states ( request , relation = relation ) for rid in states . keys ( ) : if not states [ rid ] [ 'sent' ] : return False return True | Check to see if a functionally equivalent request has already been sent | 56 | 12 |
244,370 | def is_request_complete_for_rid ( request , rid ) : broker_key = get_broker_rsp_key ( ) for unit in related_units ( rid ) : rdata = relation_get ( rid = rid , unit = unit ) if rdata . get ( broker_key ) : rsp = CephBrokerRsp ( rdata . get ( broker_key ) ) if rsp . request_id == request . request_id : if not rsp . exit_code : return True else : # The remote unit sent no reply targeted at this unit so either the # remote ceph cluster does not support unit targeted replies or it # has not processed our request yet. if rdata . get ( 'broker_rsp' ) : request_data = json . loads ( rdata [ 'broker_rsp' ] ) if request_data . get ( 'request-id' ) : log ( 'Ignoring legacy broker_rsp without unit key as remote ' 'service supports unit specific replies' , level = DEBUG ) else : log ( 'Using legacy broker_rsp as remote service does not ' 'supports unit specific replies' , level = DEBUG ) rsp = CephBrokerRsp ( rdata [ 'broker_rsp' ] ) if not rsp . exit_code : return True return False | Check if a given request has been completed on the given relation | 290 | 12 |
244,371 | def send_request_if_needed ( request , relation = 'ceph' ) : if is_request_sent ( request , relation = relation ) : log ( 'Request already sent but not complete, not sending new request' , level = DEBUG ) else : for rid in relation_ids ( relation ) : log ( 'Sending request {}' . format ( request . request_id ) , level = DEBUG ) relation_set ( relation_id = rid , broker_req = request . request ) | Send broker request if an equivalent request has not already been sent | 105 | 12 |
244,372 | def is_broker_action_done ( action , rid = None , unit = None ) : rdata = relation_get ( rid , unit ) or { } broker_rsp = rdata . get ( get_broker_rsp_key ( ) ) if not broker_rsp : return False rsp = CephBrokerRsp ( broker_rsp ) unit_name = local_unit ( ) . partition ( '/' ) [ 2 ] key = "unit_{}_ceph_broker_action.{}" . format ( unit_name , action ) kvstore = kv ( ) val = kvstore . get ( key = key ) if val and val == rsp . request_id : return True return False | Check whether broker action has completed yet . | 161 | 8 |
244,373 | def mark_broker_action_done ( action , rid = None , unit = None ) : rdata = relation_get ( rid , unit ) or { } broker_rsp = rdata . get ( get_broker_rsp_key ( ) ) if not broker_rsp : return rsp = CephBrokerRsp ( broker_rsp ) unit_name = local_unit ( ) . partition ( '/' ) [ 2 ] key = "unit_{}_ceph_broker_action.{}" . format ( unit_name , action ) kvstore = kv ( ) kvstore . set ( key = key , value = rsp . request_id ) kvstore . flush ( ) | Mark action as having been completed . | 158 | 7 |
244,374 | def get_pgs ( self , pool_size , percent_data = DEFAULT_POOL_WEIGHT , device_class = None ) : # Note: This calculation follows the approach that is provided # by the Ceph PG Calculator located at http://ceph.com/pgcalc/. validator ( value = pool_size , valid_type = int ) # Ensure that percent data is set to something - even with a default # it can be set to None, which would wreak havoc below. if percent_data is None : percent_data = DEFAULT_POOL_WEIGHT # If the expected-osd-count is specified, then use the max between # the expected-osd-count and the actual osd_count osd_list = get_osds ( self . service , device_class ) expected = config ( 'expected-osd-count' ) or 0 if osd_list : if device_class : osd_count = len ( osd_list ) else : osd_count = max ( expected , len ( osd_list ) ) # Log a message to provide some insight if the calculations claim # to be off because someone is setting the expected count and # there are more OSDs in reality. Try to make a proper guess # based upon the cluster itself. if not device_class and expected and osd_count != expected : log ( "Found more OSDs than provided expected count. " "Using the actual count instead" , INFO ) elif expected : # Use the expected-osd-count in older ceph versions to allow for # a more accurate pg calculations osd_count = expected else : # NOTE(james-page): Default to 200 for older ceph versions # which don't support OSD query from cli return LEGACY_PG_COUNT percent_data /= 100.0 target_pgs_per_osd = config ( 'pgs-per-osd' ) or DEFAULT_PGS_PER_OSD_TARGET num_pg = ( target_pgs_per_osd * osd_count * percent_data ) // pool_size # NOTE: ensure a sane minimum number of PGS otherwise we don't get any # reasonable data distribution in minimal OSD configurations if num_pg < DEFAULT_MINIMUM_PGS : num_pg = DEFAULT_MINIMUM_PGS # The CRUSH algorithm has a slight optimization for placement groups # with powers of 2 so find the nearest power of 2. If the nearest # power of 2 is more than 25% below the original value, the next # highest value is used. To do this, find the nearest power of 2 such # that 2^n <= num_pg, check to see if its within the 25% tolerance. exponent = math . floor ( math . log ( num_pg , 2 ) ) nearest = 2 ** exponent if ( num_pg - nearest ) > ( num_pg * 0.25 ) : # Choose the next highest power of 2 since the nearest is more # than 25% below the original value. return int ( nearest * 2 ) else : return int ( nearest ) | Return the number of placement groups to use when creating the pool . | 672 | 13 |
244,375 | def add_op_create_replicated_pool ( self , name , replica_count = 3 , pg_num = None , weight = None , group = None , namespace = None , app_name = None , max_bytes = None , max_objects = None ) : if pg_num and weight : raise ValueError ( 'pg_num and weight are mutually exclusive' ) self . ops . append ( { 'op' : 'create-pool' , 'name' : name , 'replicas' : replica_count , 'pg_num' : pg_num , 'weight' : weight , 'group' : group , 'group-namespace' : namespace , 'app-name' : app_name , 'max-bytes' : max_bytes , 'max-objects' : max_objects } ) | Adds an operation to create a replicated pool . | 175 | 9 |
244,376 | def add_op_create_erasure_pool ( self , name , erasure_profile = None , weight = None , group = None , app_name = None , max_bytes = None , max_objects = None ) : self . ops . append ( { 'op' : 'create-pool' , 'name' : name , 'pool-type' : 'erasure' , 'erasure-profile' : erasure_profile , 'weight' : weight , 'group' : group , 'app-name' : app_name , 'max-bytes' : max_bytes , 'max-objects' : max_objects } ) | Adds an operation to create a erasure coded pool . | 139 | 11 |
244,377 | def get_nagios_unit_name ( relation_name = 'nrpe-external-master' ) : host_context = get_nagios_hostcontext ( relation_name ) if host_context : unit = "%s:%s" % ( host_context , local_unit ( ) ) else : unit = local_unit ( ) return unit | Return the nagios unit name prepended with host_context if needed | 78 | 15 |
244,378 | def copy_nrpe_checks ( nrpe_files_dir = None ) : NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins' if nrpe_files_dir is None : # determine if "charmhelpers" is in CHARMDIR or CHARMDIR/hooks for segment in [ '.' , 'hooks' ] : nrpe_files_dir = os . path . abspath ( os . path . join ( os . getenv ( 'CHARM_DIR' ) , segment , 'charmhelpers' , 'contrib' , 'openstack' , 'files' ) ) if os . path . isdir ( nrpe_files_dir ) : break else : raise RuntimeError ( "Couldn't find charmhelpers directory" ) if not os . path . exists ( NAGIOS_PLUGINS ) : os . makedirs ( NAGIOS_PLUGINS ) for fname in glob . glob ( os . path . join ( nrpe_files_dir , "check_*" ) ) : if os . path . isfile ( fname ) : shutil . copy2 ( fname , os . path . join ( NAGIOS_PLUGINS , os . path . basename ( fname ) ) ) | Copy the nrpe checks into place | 290 | 8 |
244,379 | def write_vaultlocker_conf ( context , priority = 100 ) : charm_vl_path = "/var/lib/charm/{}/vaultlocker.conf" . format ( hookenv . service_name ( ) ) host . mkdir ( os . path . dirname ( charm_vl_path ) , perms = 0o700 ) templating . render ( source = 'vaultlocker.conf.j2' , target = charm_vl_path , context = context , perms = 0o600 ) , alternatives . install_alternative ( 'vaultlocker.conf' , '/etc/vaultlocker/vaultlocker.conf' , charm_vl_path , priority ) | Write vaultlocker configuration to disk and install alternative | 159 | 10 |
244,380 | def vault_relation_complete ( backend = None ) : vault_kv = VaultKVContext ( secret_backend = backend or VAULTLOCKER_BACKEND ) vault_kv ( ) return vault_kv . complete | Determine whether vault relation is complete | 51 | 8 |
244,381 | def retrieve_secret_id ( url , token ) : import hvac client = hvac . Client ( url = url , token = token ) response = client . _post ( '/v1/sys/wrapping/unwrap' ) if response . status_code == 200 : data = response . json ( ) return data [ 'data' ] [ 'secret_id' ] | Retrieve a response - wrapped secret_id from Vault | 82 | 11 |
244,382 | def retry_on_exception ( num_retries , base_delay = 0 , exc_type = Exception ) : def _retry_on_exception_inner_1 ( f ) : def _retry_on_exception_inner_2 ( * args , * * kwargs ) : retries = num_retries multiplier = 1 while True : try : return f ( * args , * * kwargs ) except exc_type : if not retries : raise delay = base_delay * multiplier multiplier += 1 log ( "Retrying '%s' %d more times (delay=%s)" % ( f . __name__ , retries , delay ) , level = INFO ) retries -= 1 if delay : time . sleep ( delay ) return _retry_on_exception_inner_2 return _retry_on_exception_inner_1 | If the decorated function raises exception exc_type allow num_retries retry attempts before raise the exception . | 192 | 22 |
244,383 | def _snap_exec ( commands ) : assert type ( commands ) == list retry_count = 0 return_code = None while return_code is None or return_code == SNAP_NO_LOCK : try : return_code = subprocess . check_call ( [ 'snap' ] + commands , env = os . environ ) except subprocess . CalledProcessError as e : retry_count += + 1 if retry_count > SNAP_NO_LOCK_RETRY_COUNT : raise CouldNotAcquireLockException ( 'Could not aquire lock after {} attempts' . format ( SNAP_NO_LOCK_RETRY_COUNT ) ) return_code = e . returncode log ( 'Snap failed to acquire lock, trying again in {} seconds.' . format ( SNAP_NO_LOCK_RETRY_DELAY , level = 'WARN' ) ) sleep ( SNAP_NO_LOCK_RETRY_DELAY ) return return_code | Execute snap commands . | 206 | 5 |
244,384 | def snap_remove ( packages , * flags ) : if type ( packages ) is not list : packages = [ packages ] flags = list ( flags ) message = 'Removing snap(s) "%s"' % ', ' . join ( packages ) if flags : message += ' with options "%s"' % ', ' . join ( flags ) log ( message , level = 'INFO' ) return _snap_exec ( [ 'remove' ] + flags + packages ) | Remove a snap package . | 96 | 5 |
244,385 | def validate_v2_endpoint_data ( self , endpoints , admin_port , internal_port , public_port , expected ) : self . log . debug ( 'Validating endpoint data...' ) self . log . debug ( 'actual: {}' . format ( repr ( endpoints ) ) ) found = False for ep in endpoints : self . log . debug ( 'endpoint: {}' . format ( repr ( ep ) ) ) if ( admin_port in ep . adminurl and internal_port in ep . internalurl and public_port in ep . publicurl ) : found = True actual = { 'id' : ep . id , 'region' : ep . region , 'adminurl' : ep . adminurl , 'internalurl' : ep . internalurl , 'publicurl' : ep . publicurl , 'service_id' : ep . service_id } ret = self . _validate_dict_data ( expected , actual ) if ret : return 'unexpected endpoint data - {}' . format ( ret ) if not found : return 'endpoint not found' | Validate endpoint data . | 234 | 5 |
244,386 | def validate_v3_endpoint_data ( self , endpoints , admin_port , internal_port , public_port , expected , expected_num_eps = 3 ) : self . log . debug ( 'Validating v3 endpoint data...' ) self . log . debug ( 'actual: {}' . format ( repr ( endpoints ) ) ) found = [ ] for ep in endpoints : self . log . debug ( 'endpoint: {}' . format ( repr ( ep ) ) ) if ( ( admin_port in ep . url and ep . interface == 'admin' ) or ( internal_port in ep . url and ep . interface == 'internal' ) or ( public_port in ep . url and ep . interface == 'public' ) ) : found . append ( ep . interface ) # note we ignore the links member. actual = { 'id' : ep . id , 'region' : ep . region , 'region_id' : ep . region_id , 'interface' : self . not_null , 'url' : ep . url , 'service_id' : ep . service_id , } ret = self . _validate_dict_data ( expected , actual ) if ret : return 'unexpected endpoint data - {}' . format ( ret ) if len ( found ) != expected_num_eps : return 'Unexpected number of endpoints found' | Validate keystone v3 endpoint data . | 297 | 9 |
244,387 | def convert_svc_catalog_endpoint_data_to_v3 ( self , ep_data ) : self . log . warn ( "Endpoint ID and Region ID validation is limited to not " "null checks after v2 to v3 conversion" ) for svc in ep_data . keys ( ) : assert len ( ep_data [ svc ] ) == 1 , "Unknown data format" svc_ep_data = ep_data [ svc ] [ 0 ] ep_data [ svc ] = [ { 'url' : svc_ep_data [ 'adminURL' ] , 'interface' : 'admin' , 'region' : svc_ep_data [ 'region' ] , 'region_id' : self . not_null , 'id' : self . not_null } , { 'url' : svc_ep_data [ 'publicURL' ] , 'interface' : 'public' , 'region' : svc_ep_data [ 'region' ] , 'region_id' : self . not_null , 'id' : self . not_null } , { 'url' : svc_ep_data [ 'internalURL' ] , 'interface' : 'internal' , 'region' : svc_ep_data [ 'region' ] , 'region_id' : self . not_null , 'id' : self . not_null } ] return ep_data | Convert v2 endpoint data into v3 . | 313 | 10 |
244,388 | def validate_v2_svc_catalog_endpoint_data ( self , expected , actual ) : self . log . debug ( 'Validating service catalog endpoint data...' ) self . log . debug ( 'actual: {}' . format ( repr ( actual ) ) ) for k , v in six . iteritems ( expected ) : if k in actual : ret = self . _validate_dict_data ( expected [ k ] [ 0 ] , actual [ k ] [ 0 ] ) if ret : return self . endpoint_error ( k , ret ) else : return "endpoint {} does not exist" . format ( k ) return ret | Validate service catalog endpoint data . | 138 | 7 |
244,389 | def validate_v3_svc_catalog_endpoint_data ( self , expected , actual ) : self . log . debug ( 'Validating v3 service catalog endpoint data...' ) self . log . debug ( 'actual: {}' . format ( repr ( actual ) ) ) for k , v in six . iteritems ( expected ) : if k in actual : l_expected = sorted ( v , key = lambda x : x [ 'interface' ] ) l_actual = sorted ( actual [ k ] , key = lambda x : x [ 'interface' ] ) if len ( l_actual ) != len ( l_expected ) : return ( "endpoint {} has differing number of interfaces " " - expected({}), actual({})" . format ( k , len ( l_expected ) , len ( l_actual ) ) ) for i_expected , i_actual in zip ( l_expected , l_actual ) : self . log . debug ( "checking interface {}" . format ( i_expected [ 'interface' ] ) ) ret = self . _validate_dict_data ( i_expected , i_actual ) if ret : return self . endpoint_error ( k , ret ) else : return "endpoint {} does not exist" . format ( k ) return ret | Validate the keystone v3 catalog endpoint data . | 276 | 11 |
244,390 | def validate_tenant_data ( self , expected , actual ) : self . log . debug ( 'Validating tenant data...' ) self . log . debug ( 'actual: {}' . format ( repr ( actual ) ) ) for e in expected : found = False for act in actual : a = { 'enabled' : act . enabled , 'description' : act . description , 'name' : act . name , 'id' : act . id } if e [ 'name' ] == a [ 'name' ] : found = True ret = self . _validate_dict_data ( e , a ) if ret : return "unexpected tenant data - {}" . format ( ret ) if not found : return "tenant {} does not exist" . format ( e [ 'name' ] ) return ret | Validate tenant data . | 173 | 5 |
244,391 | def validate_user_data ( self , expected , actual , api_version = None ) : self . log . debug ( 'Validating user data...' ) self . log . debug ( 'actual: {}' . format ( repr ( actual ) ) ) for e in expected : found = False for act in actual : if e [ 'name' ] == act . name : a = { 'enabled' : act . enabled , 'name' : act . name , 'email' : act . email , 'id' : act . id } if api_version == 3 : a [ 'default_project_id' ] = getattr ( act , 'default_project_id' , 'none' ) else : a [ 'tenantId' ] = act . tenantId found = True ret = self . _validate_dict_data ( e , a ) if ret : return "unexpected user data - {}" . format ( ret ) if not found : return "user {} does not exist" . format ( e [ 'name' ] ) return ret | Validate user data . | 224 | 5 |
244,392 | def validate_flavor_data ( self , expected , actual ) : self . log . debug ( 'Validating flavor data...' ) self . log . debug ( 'actual: {}' . format ( repr ( actual ) ) ) act = [ a . name for a in actual ] return self . _validate_list_data ( expected , act ) | Validate flavor data . | 75 | 5 |
244,393 | def tenant_exists ( self , keystone , tenant ) : self . log . debug ( 'Checking if tenant exists ({})...' . format ( tenant ) ) return tenant in [ t . name for t in keystone . tenants . list ( ) ] | Return True if tenant exists . | 55 | 6 |
244,394 | def keystone_wait_for_propagation ( self , sentry_relation_pairs , api_version ) : for ( sentry , relation_name ) in sentry_relation_pairs : rel = sentry . relation ( 'identity-service' , relation_name ) self . log . debug ( 'keystone relation data: {}' . format ( rel ) ) if rel . get ( 'api_version' ) != str ( api_version ) : raise Exception ( "api_version not propagated through relation" " data yet ('{}' != '{}')." "" . format ( rel . get ( 'api_version' ) , api_version ) ) | Iterate over list of sentry and relation tuples and verify that api_version has the expected value . | 148 | 22 |
244,395 | def keystone_configure_api_version ( self , sentry_relation_pairs , deployment , api_version ) : self . log . debug ( "Setting keystone preferred-api-version: '{}'" "" . format ( api_version ) ) config = { 'preferred-api-version' : api_version } deployment . d . configure ( 'keystone' , config ) deployment . _auto_wait_for_status ( ) self . keystone_wait_for_propagation ( sentry_relation_pairs , api_version ) | Configure preferred - api - version of keystone in deployment and monitor provided list of relation objects for propagation before returning to caller . | 123 | 26 |
244,396 | def authenticate_cinder_admin ( self , keystone , api_version = 2 ) : self . log . debug ( 'Authenticating cinder admin...' ) _clients = { 1 : cinder_client . Client , 2 : cinder_clientv2 . Client } return _clients [ api_version ] ( session = keystone . session ) | Authenticates admin user with cinder . | 78 | 8 |
244,397 | def authenticate_keystone ( self , keystone_ip , username , password , api_version = False , admin_port = False , user_domain_name = None , domain_name = None , project_domain_name = None , project_name = None ) : self . log . debug ( 'Authenticating with keystone...' ) if not api_version : api_version = 2 sess , auth = self . get_keystone_session ( keystone_ip = keystone_ip , username = username , password = password , api_version = api_version , admin_port = admin_port , user_domain_name = user_domain_name , domain_name = domain_name , project_domain_name = project_domain_name , project_name = project_name ) if api_version == 2 : client = keystone_client . Client ( session = sess ) else : client = keystone_client_v3 . Client ( session = sess ) # This populates the client.service_catalog client . auth_ref = auth . get_access ( sess ) return client | Authenticate with Keystone | 241 | 4 |
244,398 | def get_keystone_session ( self , keystone_ip , username , password , api_version = False , admin_port = False , user_domain_name = None , domain_name = None , project_domain_name = None , project_name = None ) : ep = self . get_keystone_endpoint ( keystone_ip , api_version = api_version , admin_port = admin_port ) if api_version == 2 : auth = v2 . Password ( username = username , password = password , tenant_name = project_name , auth_url = ep ) sess = keystone_session . Session ( auth = auth ) else : auth = v3 . Password ( user_domain_name = user_domain_name , username = username , password = password , domain_name = domain_name , project_domain_name = project_domain_name , project_name = project_name , auth_url = ep ) sess = keystone_session . Session ( auth = auth ) return ( sess , auth ) | Return a keystone session object | 227 | 6 |
244,399 | def get_keystone_endpoint ( self , keystone_ip , api_version = None , admin_port = False ) : port = 5000 if admin_port : port = 35357 base_ep = "http://{}:{}" . format ( keystone_ip . strip ( ) . decode ( 'utf-8' ) , port ) if api_version == 2 : ep = base_ep + "/v2.0" else : ep = base_ep + "/v3" return ep | Return keystone endpoint | 108 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.