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,400
def get_default_keystone_session ( self , keystone_sentry , openstack_release = None , api_version = 2 ) : self . log . debug ( 'Authenticating keystone admin...' ) # 11 => xenial_queens if api_version == 3 or ( openstack_release and openstack_release >= 11 ) : client_class = keystone_client_v3 . Client api_version = 3...
Return a keystone session object and client object assuming standard default settings
235
13
244,401
def authenticate_keystone_admin ( self , keystone_sentry , user , password , tenant = None , api_version = None , keystone_ip = None , user_domain_name = None , project_domain_name = None , project_name = None ) : self . log . debug ( 'Authenticating keystone admin...' ) if not keystone_ip : keystone_ip = keystone_sent...
Authenticates admin user with the keystone admin endpoint .
255
11
244,402
def authenticate_keystone_user ( self , keystone , user , password , tenant ) : self . log . debug ( 'Authenticating keystone user ({})...' . format ( user ) ) ep = keystone . service_catalog . url_for ( service_type = 'identity' , interface = 'publicURL' ) keystone_ip = urlparse . urlparse ( ep ) . hostname return sel...
Authenticates a regular user with the keystone public endpoint .
113
12
244,403
def authenticate_glance_admin ( self , keystone , force_v1_client = False ) : self . log . debug ( 'Authenticating glance admin...' ) ep = keystone . service_catalog . url_for ( service_type = 'image' , interface = 'adminURL' ) if not force_v1_client and keystone . session : return glance_clientv2 . Client ( "2" , sess...
Authenticates admin user with glance .
121
7
244,404
def authenticate_heat_admin ( self , keystone ) : self . log . debug ( 'Authenticating heat admin...' ) ep = keystone . service_catalog . url_for ( service_type = 'orchestration' , interface = 'publicURL' ) if keystone . session : return heat_client . Client ( endpoint = ep , session = keystone . session ) else : retur...
Authenticates the admin user with heat .
105
8
244,405
def authenticate_nova_user ( self , keystone , user , password , tenant ) : self . log . debug ( 'Authenticating nova user ({})...' . format ( user ) ) ep = keystone . service_catalog . url_for ( service_type = 'identity' , interface = 'publicURL' ) if keystone . session : return nova_client . Client ( NOVA_CLIENT_VERS...
Authenticates a regular user with nova - api .
201
11
244,406
def authenticate_swift_user ( self , keystone , user , password , tenant ) : self . log . debug ( 'Authenticating swift user ({})...' . format ( user ) ) ep = keystone . service_catalog . url_for ( service_type = 'identity' , interface = 'publicURL' ) if keystone . session : return swiftclient . Connection ( session = ...
Authenticates a regular user with swift api .
128
9
244,407
def create_flavor ( self , nova , name , ram , vcpus , disk , flavorid = "auto" , ephemeral = 0 , swap = 0 , rxtx_factor = 1.0 , is_public = True ) : try : nova . flavors . find ( name = name ) except ( exceptions . NotFound , exceptions . NoUniqueMatch ) : self . log . debug ( 'Creating flavor ({})' . format ( name ) ...
Create the specified flavor .
136
5
244,408
def glance_create_image ( self , glance , image_name , image_url , download_dir = 'tests' , hypervisor_type = None , disk_format = 'qcow2' , architecture = 'x86_64' , container_format = 'bare' ) : self . log . debug ( 'Creating glance image ({}) from ' '{}...' . format ( image_name , image_url ) ) # Download image http...
Download an image and upload it to glance validate its status and return an image object pointer . KVM defaults can override for LXD .
831
27
244,409
def create_cirros_image ( self , glance , image_name , hypervisor_type = None ) : # /!\ DEPRECATION WARNING self . log . warn ( '/!\\ DEPRECATION WARNING: use ' 'glance_create_image instead of ' 'create_cirros_image.' ) self . log . debug ( 'Creating glance cirros image ' '({})...' . format ( image_name ) ) # Get cirro...
Download the latest cirros image and upload it to glance validate and return a resource pointer .
328
18
244,410
def delete_image ( self , glance , image ) : # /!\ DEPRECATION WARNING self . log . warn ( '/!\\ DEPRECATION WARNING: use ' 'delete_resource instead of delete_image.' ) self . log . debug ( 'Deleting glance image ({})...' . format ( image ) ) return self . delete_resource ( glance . images , image , msg = 'glance image...
Delete the specified image .
92
5
244,411
def create_instance ( self , nova , image_name , instance_name , flavor ) : self . log . debug ( 'Creating instance ' '({}|{}|{})' . format ( instance_name , image_name , flavor ) ) image = nova . glance . find_image ( image_name ) flavor = nova . flavors . find ( name = flavor ) instance = nova . servers . create ( na...
Create the specified instance .
196
5
244,412
def delete_instance ( self , nova , instance ) : # /!\ DEPRECATION WARNING self . log . warn ( '/!\\ DEPRECATION WARNING: use ' 'delete_resource instead of delete_instance.' ) self . log . debug ( 'Deleting instance ({})...' . format ( instance ) ) return self . delete_resource ( nova . servers , instance , msg = 'nova...
Delete the specified instance .
92
5
244,413
def create_or_get_keypair ( self , nova , keypair_name = "testkey" ) : try : _keypair = nova . keypairs . get ( keypair_name ) self . log . debug ( 'Keypair ({}) already exists, ' 'using it.' . format ( keypair_name ) ) return _keypair except Exception : self . log . debug ( 'Keypair ({}) does not exist, ' 'creating it...
Create a new keypair or return pointer if it already exists .
135
13
244,414
def delete_resource ( self , resource , resource_id , msg = "resource" , max_wait = 120 ) : self . log . debug ( 'Deleting OpenStack resource ' '{} ({})' . format ( resource_id , msg ) ) num_before = len ( list ( resource . list ( ) ) ) resource . delete ( resource_id ) tries = 0 num_after = len ( list ( resource . lis...
Delete one openstack resource such as one instance keypair image volume stack etc . and confirm deletion within max wait time .
263
24
244,415
def resource_reaches_status ( self , resource , resource_id , expected_stat = 'available' , msg = 'resource' , max_wait = 120 ) : tries = 0 resource_stat = resource . get ( resource_id ) . status while resource_stat != expected_stat and tries < ( max_wait / 4 ) : self . log . debug ( '{} status check: ' '{} [{}:{}] {}'...
Wait for an openstack resources status to reach an expected status within a specified time . Useful to confirm that nova instances cinder vols snapshots glance images heat stacks and other resources eventually reach the expected status .
221
42
244,416
def get_ceph_pools ( self , sentry_unit ) : pools = { } cmd = 'sudo ceph osd lspools' output , code = sentry_unit . run ( cmd ) if code != 0 : msg = ( '{} `{}` returned {} ' '{}' . format ( sentry_unit . info [ 'unit_name' ] , cmd , code , output ) ) amulet . raise_status ( amulet . FAIL , msg = msg ) # For mimic ceph ...
Return a dict of ceph pools from a single ceph unit with pool name as keys pool id as vals .
264
24
244,417
def get_ceph_df ( self , sentry_unit ) : cmd = 'sudo ceph df --format=json' output , code = sentry_unit . run ( cmd ) if code != 0 : msg = ( '{} `{}` returned {} ' '{}' . format ( sentry_unit . info [ 'unit_name' ] , cmd , code , output ) ) amulet . raise_status ( amulet . FAIL , msg = msg ) return json . loads ( outpu...
Return dict of ceph df json output including ceph pool state .
109
14
244,418
def get_ceph_pool_sample ( self , sentry_unit , pool_id = 0 ) : df = self . get_ceph_df ( sentry_unit ) for pool in df [ 'pools' ] : if pool [ 'id' ] == pool_id : pool_name = pool [ 'name' ] obj_count = pool [ 'stats' ] [ 'objects' ] kb_used = pool [ 'stats' ] [ 'kb_used' ] self . log . debug ( 'Ceph {} pool (ID {}): {...
Take a sample of attributes of a ceph pool returning ceph pool name object count and disk space used for the specified pool ID number .
162
28
244,419
def validate_ceph_pool_samples ( self , samples , sample_type = "resource pool" ) : original , created , deleted = range ( 3 ) if samples [ created ] <= samples [ original ] or samples [ deleted ] >= samples [ created ] : return ( 'Ceph {} samples ({}) ' 'unexpected.' . format ( sample_type , samples ) ) else : self . ...
Validate ceph pool samples taken over time such as pool object counts or pool kb used before adding after adding and after deleting items which affect those pool attributes . The 2nd element is expected to be greater than the 1st ; 3rd is expected to be less than the 2nd .
113
58
244,420
def rmq_wait_for_cluster ( self , deployment , init_sleep = 15 , timeout = 1200 ) : if init_sleep : time . sleep ( init_sleep ) message = re . compile ( '^Unit is ready and clustered$' ) deployment . _auto_wait_for_status ( message = message , timeout = timeout , include_only = [ 'rabbitmq-server' ] )
Wait for rmq units extended status to show cluster readiness after an optional initial sleep period . Initial sleep is likely necessary to be effective following a config change as status message may not instantly update to non - ready .
89
42
244,421
def get_rmq_cluster_status ( self , sentry_unit ) : cmd = 'rabbitmqctl cluster_status' output , _ = self . run_cmd_unit ( sentry_unit , cmd ) self . log . debug ( '{} cluster_status:\n{}' . format ( sentry_unit . info [ 'unit_name' ] , output ) ) return str ( output )
Execute rabbitmq cluster status command on a unit and return the full output .
92
17
244,422
def get_rmq_cluster_running_nodes ( self , sentry_unit ) : # NOTE(beisner): rabbitmqctl cluster_status output is not # json-parsable, do string chop foo, then json.loads that. str_stat = self . get_rmq_cluster_status ( sentry_unit ) if 'running_nodes' in str_stat : pos_start = str_stat . find ( "{running_nodes," ) + 15...
Parse rabbitmqctl cluster_status output string return list of running rabbitmq cluster nodes .
182
21
244,423
def validate_rmq_cluster_running_nodes ( self , sentry_units ) : host_names = self . get_unit_hostnames ( sentry_units ) errors = [ ] # Query every unit for cluster_status running nodes for query_unit in sentry_units : query_unit_name = query_unit . info [ 'unit_name' ] running_nodes = self . get_rmq_cluster_running_no...
Check that all rmq unit hostnames are represented in the cluster_status output of all units .
249
20
244,424
def rmq_ssl_is_enabled_on_unit ( self , sentry_unit , port = None ) : host = sentry_unit . info [ 'public-address' ] unit_name = sentry_unit . info [ 'unit_name' ] conf_file = '/etc/rabbitmq/rabbitmq.config' conf_contents = str ( self . file_contents_safe ( sentry_unit , conf_file , max_wait = 16 ) ) # Checks conf_ssl ...
Check a single juju rmq unit for ssl and port in the config file .
383
18
244,425
def validate_rmq_ssl_enabled_units ( self , sentry_units , port = None ) : for sentry_unit in sentry_units : if not self . rmq_ssl_is_enabled_on_unit ( sentry_unit , port = port ) : return ( 'Unexpected condition: ssl is disabled on unit ' '({})' . format ( sentry_unit . info [ 'unit_name' ] ) ) return None
Check that ssl is enabled on rmq juju sentry units .
100
15
244,426
def validate_rmq_ssl_disabled_units ( self , sentry_units ) : for sentry_unit in sentry_units : if self . rmq_ssl_is_enabled_on_unit ( sentry_unit ) : return ( 'Unexpected condition: ssl is enabled on unit ' '({})' . format ( sentry_unit . info [ 'unit_name' ] ) ) return None
Check that ssl is enabled on listed rmq juju sentry units .
91
16
244,427
def configure_rmq_ssl_on ( self , sentry_units , deployment , port = None , max_wait = 60 ) : self . log . debug ( 'Setting ssl charm config option: on' ) # Enable RMQ SSL config = { 'ssl' : 'on' } if port : config [ 'ssl_port' ] = port deployment . d . configure ( 'rabbitmq-server' , config ) # Wait for unit status se...
Turn ssl charm config option on with optional non - default ssl port specification . Confirm that it is enabled on every unit .
224
27
244,428
def configure_rmq_ssl_off ( self , sentry_units , deployment , max_wait = 60 ) : self . log . debug ( 'Setting ssl charm config option: off' ) # Disable RMQ SSL config = { 'ssl' : 'off' } deployment . d . configure ( 'rabbitmq-server' , config ) # Wait for unit status self . rmq_wait_for_cluster ( deployment ) # Confir...
Turn ssl charm config option off confirm that it is disabled on every unit .
199
16
244,429
def connect_amqp_by_unit ( self , sentry_unit , ssl = False , port = None , fatal = True , username = "testuser1" , password = "changeme" ) : host = sentry_unit . info [ 'public-address' ] unit_name = sentry_unit . info [ 'unit_name' ] # Default port logic if port is not specified if ssl and not port : port = 5671 elif...
Establish and return a pika amqp connection to the rabbitmq service running on a rmq juju unit .
326
26
244,430
def publish_amqp_message_by_unit ( self , sentry_unit , message , queue = "test" , ssl = False , username = "testuser1" , password = "changeme" , port = None ) : self . log . debug ( 'Publishing message to {} queue:\n{}' . format ( queue , message ) ) connection = self . connect_amqp_by_unit ( sentry_unit , ssl = ssl ,...
Publish an amqp message to a rmq juju unit .
303
15
244,431
def get_amqp_message_by_unit ( self , sentry_unit , queue = "test" , username = "testuser1" , password = "changeme" , ssl = False , port = None ) : connection = self . connect_amqp_by_unit ( sentry_unit , ssl = ssl , port = port , username = username , password = password ) channel = connection . channel ( ) method_fra...
Get an amqp message from a rmq juju unit .
192
14
244,432
def validate_memcache ( self , sentry_unit , conf , os_release , earliest_release = 5 , section = 'keystone_authtoken' , check_kvs = None ) : if os_release < earliest_release : self . log . debug ( 'Skipping memcache checks for deployment. {} <' 'mitaka' . format ( os_release ) ) return _kvs = check_kvs or { 'memcached...
Check Memcache is running and is configured to be used
599
11
244,433
def acquire ( self , lock ) : unit = hookenv . local_unit ( ) ts = self . requests [ unit ] . get ( lock ) if not ts : # If there is no outstanding request on the peers relation, # create one. self . requests . setdefault ( lock , { } ) self . requests [ unit ] [ lock ] = _timestamp ( ) self . msg ( 'Requested {}' . fo...
Acquire the named lock non - blocking .
199
9
244,434
def granted ( self , lock ) : unit = hookenv . local_unit ( ) ts = self . requests [ unit ] . get ( lock ) if ts and self . grants . get ( unit , { } ) . get ( lock ) == ts : return True return False
Return True if a previously requested lock has been granted
57
10
244,435
def request_timestamp ( self , lock ) : ts = self . requests [ hookenv . local_unit ( ) ] . get ( lock , None ) if ts is not None : return datetime . strptime ( ts , _timestamp_format )
Return the timestamp of our outstanding request for lock or None .
55
12
244,436
def grant ( self , lock , unit ) : if not hookenv . is_leader ( ) : return False # Not the leader, so we cannot grant. # Set of units already granted the lock. granted = set ( ) for u in self . grants : if lock in self . grants [ u ] : granted . add ( u ) if unit in granted : return True # Already granted. # Ordered li...
Maybe grant the lock to a unit .
298
8
244,437
def released ( self , unit , lock , timestamp ) : interval = _utcnow ( ) - timestamp self . msg ( 'Leader released {} from {}, held {}' . format ( lock , unit , interval ) )
Called on the leader when it has released a lock .
46
12
244,438
def require ( self , lock , guard_func , * guard_args , * * guard_kw ) : def decorator ( f ) : @ wraps ( f ) def wrapper ( * args , * * kw ) : if self . granted ( lock ) : self . msg ( 'Granted {}' . format ( lock ) ) return f ( * args , * * kw ) if guard_func ( * guard_args , * * guard_kw ) and self . acquire ( lock )...
Decorate a function to be run only when a lock is acquired .
123
14
244,439
def msg ( self , msg ) : hookenv . log ( 'coordinator.{} {}' . format ( self . _name ( ) , msg ) , level = hookenv . INFO )
Emit a message . Override to customize log spam .
41
12
244,440
def deprecate ( warning , date = None , log = None ) : def wrap ( f ) : @ functools . wraps ( f ) def wrapped_f ( * args , * * kwargs ) : try : module = inspect . getmodule ( f ) file = inspect . getsourcefile ( f ) lines = inspect . getsourcelines ( f ) f_name = "{}-{}-{}..{}-{}" . format ( module . __name__ , file , ...
Add a deprecation warning the first time the function is used . The date which is a string in semi - ISO8660 format indicate the year - month that the function is officially going to be removed .
271
42
244,441
def download ( self , source , dest ) : # propagate all exceptions # URLError, OSError, etc proto , netloc , path , params , query , fragment = urlparse ( source ) if proto in ( 'http' , 'https' ) : auth , barehost = splituser ( netloc ) if auth is not None : source = urlunparse ( ( proto , barehost , path , params , q...
Download an archive file .
244
5
244,442
def install ( self , source , dest = None , checksum = None , hash_type = 'sha1' ) : url_parts = self . parse_url ( source ) dest_dir = os . path . join ( os . environ . get ( 'CHARM_DIR' ) , 'fetched' ) if not os . path . exists ( dest_dir ) : mkdir ( dest_dir , perms = 0o755 ) dld_file = os . path . join ( dest_dir ,...
Download and install an archive file with optional checksum validation .
302
12
244,443
def set_trace ( addr = DEFAULT_ADDR , port = DEFAULT_PORT ) : atexit . register ( close_port , port ) try : log ( "Starting a remote python debugger session on %s:%s" % ( addr , port ) ) open_port ( port ) debugger = Rpdb ( addr = addr , port = port ) debugger . set_trace ( sys . _getframe ( ) . f_back ) except Excepti...
Set a trace point using the remote debugger
123
8
244,444
def device_info ( device ) : status = subprocess . check_output ( [ 'ibstat' , device , '-s' ] ) . splitlines ( ) regexes = { "CA type: (.*)" : "device_type" , "Number of ports: (.*)" : "num_ports" , "Firmware version: (.*)" : "fw_ver" , "Hardware version: (.*)" : "hw_ver" , "Node GUID: (.*)" : "node_guid" , "System im...
Returns a DeviceInfo object with the current device settings
185
10
244,445
def ipoib_interfaces ( ) : interfaces = [ ] for interface in network_interfaces ( ) : try : driver = re . search ( '^driver: (.+)$' , subprocess . check_output ( [ 'ethtool' , '-i' , interface ] ) , re . M ) . group ( 1 ) if driver in IPOIB_DRIVERS : interfaces . append ( interface ) except Exception : log ( "Skipping ...
Return a list of IPOIB capable ethernet interfaces
110
10
244,446
def get_audits ( ) : audits = [ TemplatedFile ( '/etc/login.defs' , LoginContext ( ) , template_dir = TEMPLATES_DIR , user = 'root' , group = 'root' , mode = 0o0444 ) ] return audits
Get OS hardening login . defs audits .
62
10
244,447
def _get_defaults ( modules ) : default = os . path . join ( os . path . dirname ( __file__ ) , 'defaults/%s.yaml' % ( modules ) ) return yaml . safe_load ( open ( default ) )
Load the default config for the provided modules .
58
9
244,448
def _get_schema ( modules ) : schema = os . path . join ( os . path . dirname ( __file__ ) , 'defaults/%s.yaml.schema' % ( modules ) ) return yaml . safe_load ( open ( schema ) )
Load the config schema for the provided modules .
61
9
244,449
def _get_user_provided_overrides ( modules ) : overrides = os . path . join ( os . environ [ 'JUJU_CHARM_DIR' ] , 'hardening.yaml' ) if os . path . exists ( overrides ) : log ( "Found user-provided config overrides file '%s'" % ( overrides ) , level = DEBUG ) settings = yaml . safe_load ( open ( overrides ) ) if settin...
Load user - provided config overrides .
197
8
244,450
def _apply_overrides ( settings , overrides , schema ) : if overrides : for k , v in six . iteritems ( overrides ) : if k in schema : if schema [ k ] is None : settings [ k ] = v elif type ( schema [ k ] ) is dict : settings [ k ] = _apply_overrides ( settings [ k ] , overrides [ k ] , schema [ k ] ) else : raise Excep...
Get overrides config overlayed onto modules defaults .
148
10
244,451
def ensure_permissions ( path , user , group , permissions , maxdepth = - 1 ) : if not os . path . exists ( path ) : log ( "File '%s' does not exist - cannot set permissions" % ( path ) , level = WARNING ) return _user = pwd . getpwnam ( user ) os . chown ( path , _user . pw_uid , grp . getgrnam ( group ) . gr_gid ) os...
Ensure permissions for path .
203
6
244,452
def create ( sysctl_dict , sysctl_file , ignore = False ) : if type ( sysctl_dict ) is not dict : try : sysctl_dict_parsed = yaml . safe_load ( sysctl_dict ) except yaml . YAMLError : log ( "Error parsing YAML sysctl_dict: {}" . format ( sysctl_dict ) , level = ERROR ) return else : sysctl_dict_parsed = sysctl_dict wit...
Creates a sysctl . conf file from a YAML associative array
231
16
244,453
def canonical_url ( configs , endpoint_type = PUBLIC ) : scheme = _get_scheme ( configs ) address = resolve_address ( endpoint_type ) if is_ipv6 ( address ) : address = "[{}]" . format ( address ) return '%s://%s' % ( scheme , address )
Returns the correct HTTP URL to this host given the state of HTTPS configuration hacluster and charm configuration .
71
21
244,454
def _get_address_override ( endpoint_type = PUBLIC ) : override_key = ADDRESS_MAP [ endpoint_type ] [ 'override' ] addr_override = config ( override_key ) if not addr_override : return None else : return addr_override . format ( service_name = service_name ( ) )
Returns any address overrides that the user has defined based on the endpoint type .
76
16
244,455
def resolve_address ( endpoint_type = PUBLIC , override = True ) : resolved_address = None if override : resolved_address = _get_address_override ( endpoint_type ) if resolved_address : return resolved_address vips = config ( 'vip' ) if vips : vips = vips . split ( ) net_type = ADDRESS_MAP [ endpoint_type ] [ 'config' ...
Return unit address depending on net config .
511
8
244,456
def hugepage_support ( user , group = 'hugetlb' , nr_hugepages = 256 , max_map_count = 65536 , mnt_point = '/run/hugepages/kvm' , pagesize = '2MB' , mount = True , set_shmmax = False ) : group_info = add_group ( group ) gid = group_info . gr_gid add_user_to_group ( user , group ) if max_map_count < 2 * nr_hugepages : m...
Enable hugepages on system .
480
6
244,457
def ensure_compliance ( self ) : if not self . modules : return try : loaded_modules = self . _get_loaded_modules ( ) non_compliant_modules = [ ] for module in self . modules : if module in loaded_modules : log ( "Module '%s' is enabled but should not be." % ( module ) , level = INFO ) non_compliant_modules . append ( ...
Ensures that the modules are not loaded .
179
10
244,458
def _get_loaded_modules ( ) : output = subprocess . check_output ( [ 'apache2ctl' , '-M' ] ) if six . PY3 : output = output . decode ( 'utf-8' ) modules = [ ] for line in output . splitlines ( ) : # Each line of the enabled module output looks like: # module_name (static|shared) # Plus a header line at the top of the o...
Returns the modules which are enabled in Apache .
147
9
244,459
def _disable_module ( module ) : try : subprocess . check_call ( [ 'a2dismod' , module ] ) except subprocess . CalledProcessError as e : # Note: catch error here to allow the attempt of disabling # multiple modules in one go rather than failing after the # first module fails. log ( 'Error occurred disabling module %s. ...
Disables the specified module in Apache .
99
8
244,460
def get_template_path ( template_dir , path ) : return os . path . join ( template_dir , os . path . basename ( path ) )
Returns the template file which would be used to render the path .
35
13
244,461
def render_and_write ( template_dir , path , context ) : env = Environment ( loader = FileSystemLoader ( template_dir ) ) template_file = os . path . basename ( path ) template = env . get_template ( template_file ) log ( 'Rendering from template: %s' % template . name , level = DEBUG ) rendered_content = template . re...
Renders the specified template into the file .
150
9
244,462
def get_audits ( ) : audits = [ AptConfig ( [ { 'key' : 'APT::Get::AllowUnauthenticated' , 'expected' : 'false' } ] ) ] settings = get_settings ( 'os' ) clean_packages = settings [ 'security' ] [ 'packages_clean' ] if clean_packages : security_packages = settings [ 'security' ] [ 'packages_list' ] if security_packages ...
Get OS hardening apt audits .
114
7
244,463
def get_audits ( ) : audits = [ ] settings = utils . get_settings ( 'os' ) if settings [ 'auth' ] [ 'pam_passwdqc_enable' ] : audits . append ( PasswdqcPAM ( '/etc/passwdqc.conf' ) ) if settings [ 'auth' ] [ 'retries' ] : audits . append ( Tally2PAM ( '/usr/share/pam-configs/tally2' ) ) else : audits . append ( Deleted...
Get OS hardening PAM authentication audits .
139
9
244,464
def install_ansible_support ( from_ppa = True , ppa_location = 'ppa:rquillo/ansible' ) : if from_ppa : charmhelpers . fetch . add_source ( ppa_location ) charmhelpers . fetch . apt_update ( fatal = True ) charmhelpers . fetch . apt_install ( 'ansible' ) with open ( ansible_hosts_path , 'w+' ) as hosts_file : hosts_file...
Installs the ansible package .
130
7
244,465
def execute ( self , args ) : hook_name = os . path . basename ( args [ 0 ] ) extra_vars = None if hook_name in self . _actions : extra_vars = self . _actions [ hook_name ] ( args [ 1 : ] ) else : super ( AnsibleHooks , self ) . execute ( args ) charmhelpers . contrib . ansible . apply_playbook ( self . playbook_path ,...
Execute the hook followed by the playbook using the hook as tag .
116
14
244,466
def action ( self , * action_names ) : def action_wrapper ( decorated ) : @ functools . wraps ( decorated ) def wrapper ( argv ) : kwargs = dict ( arg . split ( '=' ) for arg in argv ) try : return decorated ( * * kwargs ) except TypeError as e : if decorated . __doc__ : e . args += ( decorated . __doc__ , ) raise self...
Decorator registering them as actions
146
7
244,467
def get_logger ( self , name = "deployment-logger" , level = logging . DEBUG ) : log = logging logger = log . getLogger ( name ) fmt = log . Formatter ( "%(asctime)s %(funcName)s " "%(levelname)s: %(message)s" ) handler = log . StreamHandler ( stream = sys . stdout ) handler . setLevel ( level ) handler . setFormatter ...
Get a logger object that will log to stdout .
119
11
244,468
def _determine_branch_locations ( self , other_services ) : self . log . info ( 'OpenStackAmuletDeployment: determine branch locations' ) # Charms outside the ~openstack-charmers base_charms = { 'mysql' : [ 'trusty' ] , 'mongodb' : [ 'trusty' ] , 'nrpe' : [ 'trusty' , 'xenial' ] , } for svc in other_services : # If a l...
Determine the branch locations for the other services .
340
11
244,469
def _auto_wait_for_status ( self , message = None , exclude_services = None , include_only = None , timeout = None ) : if not timeout : timeout = int ( os . environ . get ( 'AMULET_SETUP_TIMEOUT' , 1800 ) ) self . log . info ( 'Waiting for extended status on units for {}s...' '' . format ( timeout ) ) all_services = se...
Wait for all units to have a specific extended status except for any defined as excluded . Unless specified via message any status containing any case of ready will be considered a match .
438
34
244,470
def _get_openstack_release ( self ) : # Must be ordered by OpenStack release (not by Ubuntu release): for i , os_pair in enumerate ( OPENSTACK_RELEASES_PAIRS ) : setattr ( self , os_pair , i ) releases = { ( 'trusty' , None ) : self . trusty_icehouse , ( 'trusty' , 'cloud:trusty-kilo' ) : self . trusty_kilo , ( 'trusty...
Get openstack release .
447
5
244,471
def _get_openstack_release_string ( self ) : releases = OrderedDict ( [ ( 'trusty' , 'icehouse' ) , ( 'xenial' , 'mitaka' ) , ( 'yakkety' , 'newton' ) , ( 'zesty' , 'ocata' ) , ( 'artful' , 'pike' ) , ( 'bionic' , 'queens' ) , ( 'cosmic' , 'rocky' ) , ( 'disco' , 'stein' ) , ] ) if self . openstack : os_origin = self ....
Get openstack release string .
182
6
244,472
def get_ceph_expected_pools ( self , radosgw = False ) : if self . _get_openstack_release ( ) == self . trusty_icehouse : # Icehouse pools = [ 'data' , 'metadata' , 'rbd' , 'cinder-ceph' , 'glance' ] elif ( self . trusty_kilo <= self . _get_openstack_release ( ) <= self . zesty_ocata ) : # Kilo through Ocata pools = [ ...
Return a list of expected ceph pools in a ceph + cinder + glance test scenario based on OpenStack release and whether ceph radosgw is flagged as present or not .
202
39
244,473
def get_platform ( ) : # linux_distribution is deprecated and will be removed in Python 3.7 # Warings *not* disabled, as we certainly need to fix this. tuple_platform = platform . linux_distribution ( ) current_platform = tuple_platform [ 0 ] if "Ubuntu" in current_platform : return "ubuntu" elif "CentOS" in current_pl...
Return the current OS platform .
153
6
244,474
def current_version_string ( ) : return "{0}.{1}.{2}" . format ( sys . version_info . major , sys . version_info . minor , sys . version_info . micro )
Current system python version as string major . minor . micro
46
11
244,475
def get_audits ( ) : if subprocess . call ( [ 'which' , 'mysql' ] , stdout = subprocess . PIPE ) != 0 : log ( "MySQL does not appear to be installed on this node - " "skipping mysql hardening" , level = WARNING ) return [ ] settings = utils . get_settings ( 'mysql' ) hardening_settings = settings [ 'hardening' ] my_cnf...
Get MySQL hardening config audits .
330
7
244,476
def service_reload ( service_name , restart_on_failure = False , * * kwargs ) : service_result = service ( 'reload' , service_name , * * kwargs ) if not service_result and restart_on_failure : service_result = service ( 'restart' , service_name , * * kwargs ) return service_result
Reload a system service optionally falling back to restart if reload fails .
85
14
244,477
def service_pause ( service_name , init_dir = "/etc/init" , initd_dir = "/etc/init.d" , * * kwargs ) : stopped = True if service_running ( service_name , * * kwargs ) : stopped = service_stop ( service_name , * * kwargs ) upstart_file = os . path . join ( init_dir , "{}.conf" . format ( service_name ) ) sysv_file = os ...
Pause a system service .
311
5
244,478
def service_resume ( service_name , init_dir = "/etc/init" , initd_dir = "/etc/init.d" , * * kwargs ) : upstart_file = os . path . join ( init_dir , "{}.conf" . format ( service_name ) ) sysv_file = os . path . join ( initd_dir , service_name ) if init_is_systemd ( ) : service ( 'unmask' , service_name ) service ( 'ena...
Resume a system service .
308
6
244,479
def service ( action , service_name , * * kwargs ) : if init_is_systemd ( ) : cmd = [ 'systemctl' , action , service_name ] else : cmd = [ 'service' , service_name , action ] for key , value in six . iteritems ( kwargs ) : parameter = '%s=%s' % ( key , value ) cmd . append ( parameter ) return subprocess . call ( cmd )...
Control a system service .
101
5
244,480
def service_running ( service_name , * * kwargs ) : if init_is_systemd ( ) : return service ( 'is-active' , service_name ) else : if os . path . exists ( _UPSTART_CONF . format ( service_name ) ) : try : cmd = [ 'status' , service_name ] for key , value in six . iteritems ( kwargs ) : parameter = '%s=%s' % ( key , valu...
Determine whether a system service is running .
257
10
244,481
def adduser ( username , password = None , shell = '/bin/bash' , system_user = False , primary_group = None , secondary_groups = None , uid = None , home_dir = None ) : try : user_info = pwd . getpwnam ( username ) log ( 'user {0} already exists!' . format ( username ) ) if uid : user_info = pwd . getpwuid ( int ( uid ...
Add a user to the system .
355
7
244,482
def user_exists ( username ) : try : pwd . getpwnam ( username ) user_exists = True except KeyError : user_exists = False return user_exists
Check if a user exists
42
5
244,483
def uid_exists ( uid ) : try : pwd . getpwuid ( uid ) uid_exists = True except KeyError : uid_exists = False return uid_exists
Check if a uid exists
48
6
244,484
def group_exists ( groupname ) : try : grp . getgrnam ( groupname ) group_exists = True except KeyError : group_exists = False return group_exists
Check if a group exists
43
5
244,485
def gid_exists ( gid ) : try : grp . getgrgid ( gid ) gid_exists = True except KeyError : gid_exists = False return gid_exists
Check if a gid exists
48
6
244,486
def add_group ( group_name , system_group = False , gid = None ) : try : group_info = grp . getgrnam ( group_name ) log ( 'group {0} already exists!' . format ( group_name ) ) if gid : group_info = grp . getgrgid ( gid ) log ( 'group with gid {0} already exists!' . format ( gid ) ) except KeyError : log ( 'creating gro...
Add a group to the system
153
6
244,487
def chage ( username , lastday = None , expiredate = None , inactive = None , mindays = None , maxdays = None , root = None , warndays = None ) : cmd = [ 'chage' ] if root : cmd . extend ( [ '--root' , root ] ) if lastday : cmd . extend ( [ '--lastday' , lastday ] ) if expiredate : cmd . extend ( [ '--expiredate' , exp...
Change user password expiry information
196
6
244,488
def rsync ( from_path , to_path , flags = '-r' , options = None , timeout = None ) : options = options or [ '--delete' , '--executability' ] cmd = [ '/usr/bin/rsync' , flags ] if timeout : cmd = [ 'timeout' , str ( timeout ) ] + cmd cmd . extend ( options ) cmd . append ( from_path ) cmd . append ( to_path ) log ( " " ...
Replicate the contents of a path
141
7
244,489
def write_file ( path , content , owner = 'root' , group = 'root' , perms = 0o444 ) : uid = pwd . getpwnam ( owner ) . pw_uid gid = grp . getgrnam ( group ) . gr_gid # lets see if we can grab the file and compare the context, to avoid doing # a write. existing_content = None existing_uid , existing_gid , existing_perms...
Create or overwrite a file with the contents of a byte string .
471
13
244,490
def mount ( device , mountpoint , options = None , persist = False , filesystem = "ext3" ) : cmd_args = [ 'mount' ] if options is not None : cmd_args . extend ( [ '-o' , options ] ) cmd_args . extend ( [ device , mountpoint ] ) try : subprocess . check_output ( cmd_args ) except subprocess . CalledProcessError as e : l...
Mount a filesystem at a particular mountpoint
140
8
244,491
def umount ( mountpoint , persist = False ) : cmd_args = [ 'umount' , mountpoint ] try : subprocess . check_output ( cmd_args ) except subprocess . CalledProcessError as e : log ( 'Error unmounting {}\n{}' . format ( mountpoint , e . output ) ) return False if persist : return fstab_remove ( mountpoint ) return True
Unmount a filesystem
88
4
244,492
def fstab_mount ( mountpoint ) : cmd_args = [ 'mount' , mountpoint ] try : subprocess . check_output ( cmd_args ) except subprocess . CalledProcessError as e : log ( 'Error unmounting {}\n{}' . format ( mountpoint , e . output ) ) return False return True
Mount filesystem using fstab
73
5
244,493
def file_hash ( path , hash_type = 'md5' ) : if os . path . exists ( path ) : h = getattr ( hashlib , hash_type ) ( ) with open ( path , 'rb' ) as source : h . update ( source . read ( ) ) return h . hexdigest ( ) else : return None
Generate a hash checksum of the contents of path or None if not found .
75
17
244,494
def check_hash ( path , checksum , hash_type = 'md5' ) : actual_checksum = file_hash ( path , hash_type ) if checksum != actual_checksum : raise ChecksumError ( "'%s' != '%s'" % ( checksum , actual_checksum ) )
Validate a file using a cryptographic checksum .
69
10
244,495
def restart_on_change ( restart_map , stopstart = False , restart_functions = None ) : def wrap ( f ) : @ functools . wraps ( f ) def wrapped_f ( * args , * * kwargs ) : return restart_on_change_helper ( ( lambda : f ( * args , * * kwargs ) ) , restart_map , stopstart , restart_functions ) return wrapped_f return wrap
Restart services based on configuration files changing
98
8
244,496
def restart_on_change_helper ( lambda_f , restart_map , stopstart = False , restart_functions = None ) : if restart_functions is None : restart_functions = { } checksums = { path : path_hash ( path ) for path in restart_map } r = lambda_f ( ) # create a list of lists of the services to restart restarts = [ restart_map ...
Helper function to perform the restart_on_change function .
229
12
244,497
def pwgen ( length = None ) : if length is None : # A random length is ok to use a weak PRNG length = random . choice ( range ( 35 , 45 ) ) alphanumeric_chars = [ l for l in ( string . ascii_letters + string . digits ) if l not in 'l0QD1vAEIOUaeiou' ] # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the # ac...
Generate a random pasword .
160
7
244,498
def is_phy_iface ( interface ) : if interface : sys_net = '/sys/class/net' if os . path . isdir ( sys_net ) : for iface in glob . glob ( os . path . join ( sys_net , '*' ) ) : if '/virtual/' in os . path . realpath ( iface ) : continue if interface == os . path . basename ( iface ) : return True return False
Returns True if interface is not virtual otherwise False .
98
10
244,499
def get_bond_master ( interface ) : if interface : iface_path = '/sys/class/net/%s' % ( interface ) if os . path . exists ( iface_path ) : if '/virtual/' in os . path . realpath ( iface_path ) : return None master = os . path . join ( iface_path , 'master' ) if os . path . exists ( master ) : master = os . path . realp...
Returns bond master if interface is bond slave otherwise None .
147
11