idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
245,400
def create_cirros_image ( self , glance , image_name , hypervisor_type = None ) : self . log . warn ( '/!\\ DEPRECATION WARNING: use ' 'glance_create_image instead of ' 'create_cirros_image.' ) self . log . debug ( 'Creating glance cirros image ' '({})...' . format ( image_name ) ) http_proxy = os . getenv ( 'AMULET_H...
Download the latest cirros image and upload it to glance validate and return a resource pointer .
245,401
def delete_image ( self , glance , image ) : 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 .
245,402
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 .
245,403
def delete_instance ( self , nova , instance ) : 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 instance' )
Delete the specified instance .
245,404
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 .
245,405
def create_cinder_volume ( self , cinder , vol_name = "demo-vol" , vol_size = 1 , img_id = None , src_vol_id = None , snap_id = None ) : if img_id and not src_vol_id and not snap_id : self . log . debug ( 'Creating cinder volume from glance image...' ) bootable = 'true' elif src_vol_id and not img_id and not snap_id : ...
Create cinder volume optionally from a glance image OR optionally as a clone of an existing volume OR optionally from a snapshot . Wait for the new volume status to reach the expected status validate and return a resource pointer .
245,406
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 .
245,407
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 .
245,408
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 ) output = output ....
Return a dict of ceph pools from a single ceph unit with pool name as keys pool id as vals .
245,409
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 .
245,410
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 .
245,411
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 .
245,412
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 .
245,413
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 .
245,414
def get_rmq_cluster_running_nodes ( self , sentry_unit ) : str_stat = self . get_rmq_cluster_status ( sentry_unit ) if 'running_nodes' in str_stat : pos_start = str_stat . find ( "{running_nodes," ) + 15 pos_end = str_stat . find ( "]}," , pos_start ) + 1 str_run_nodes = str_stat [ pos_start : pos_end ] . replace ( "'"...
Parse rabbitmqctl cluster_status output string return list of running rabbitmq cluster nodes .
245,415
def validate_rmq_cluster_running_nodes ( self , sentry_units ) : host_names = self . get_unit_hostnames ( sentry_units ) errors = [ ] for query_unit in sentry_units : query_unit_name = query_unit . info [ 'unit_name' ] running_nodes = self . get_rmq_cluster_running_nodes ( query_unit ) for validate_unit in sentry_units...
Check that all rmq unit hostnames are represented in the cluster_status output of all units .
245,416
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 ) ) conf_ssl = 'ssl' i...
Check a single juju rmq unit for ssl and port in the config file .
245,417
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 .
245,418
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 .
245,419
def configure_rmq_ssl_on ( self , sentry_units , deployment , port = None , max_wait = 60 ) : self . log . debug ( 'Setting ssl charm config option: on' ) config = { 'ssl' : 'on' } if port : config [ 'ssl_port' ] = port deployment . d . configure ( 'rabbitmq-server' , config ) self . rmq_wait_for_cluster ( deployment ...
Turn ssl charm config option on with optional non - default ssl port specification . Confirm that it is enabled on every unit .
245,420
def configure_rmq_ssl_off ( self , sentry_units , deployment , max_wait = 60 ) : self . log . debug ( 'Setting ssl charm config option: off' ) config = { 'ssl' : 'off' } deployment . d . configure ( 'rabbitmq-server' , config ) self . rmq_wait_for_cluster ( deployment ) tries = 0 ret = self . validate_rmq_ssl_disabled...
Turn ssl charm config option off confirm that it is disabled on every unit .
245,421
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' ] if ssl and not port : port = 5671 elif not ssl and not port : port = 5672 self . log...
Establish and return a pika amqp connection to the rabbitmq service running on a rmq juju unit .
245,422
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 .
245,423
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 .
245,424
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
245,425
def acquire ( self , lock ) : unit = hookenv . local_unit ( ) ts = self . requests [ unit ] . get ( lock ) if not ts : self . requests . setdefault ( lock , { } ) self . requests [ unit ] [ lock ] = _timestamp ( ) self . msg ( 'Requested {}' . format ( lock ) ) if self . granted ( lock ) : self . msg ( 'Acquired {}' . ...
Acquire the named lock non - blocking .
245,426
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
245,427
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 .
245,428
def grant ( self , lock , unit ) : if not hookenv . is_leader ( ) : return False granted = set ( ) for u in self . grants : if lock in self . grants [ u ] : granted . add ( u ) if unit in granted : return True reqs = set ( ) for u in self . requests : if u in granted : continue for _lock , ts in self . requests [ u ] ....
Maybe grant the lock to a unit .
245,429
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 .
245,430
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 ) : r...
Decorate a function to be run only when a lock is acquired .
245,431
def msg ( self , msg ) : hookenv . log ( 'coordinator.{} {}' . format ( self . _name ( ) , msg ) , level = hookenv . INFO )
Emit a message . Override to customize log spam .
245,432
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 , l...
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 .
245,433
def download ( self , source , dest ) : 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 , query , fragment ) ) username , password = splitpassw...
Download an archive file .
245,434
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 .
245,435
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
245,436
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
245,437
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
245,438
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 .
245,439
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 .
245,440
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 .
245,441
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 .
245,442
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 .
245,443
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 .
245,444
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
245,445
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 .
245,446
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 .
245,447
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 .
245,448
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 .
245,449
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 .
245,450
def _get_loaded_modules ( ) : output = subprocess . check_output ( [ 'apache2ctl' , '-M' ] ) if six . PY3 : output = output . decode ( 'utf-8' ) modules = [ ] for line in output . splitlines ( ) : matcher = re . search ( r'^ (\S*)_module (\S*)' , line ) if matcher : modules . append ( matcher . group ( 1 ) ) return mod...
Returns the modules which are enabled in Apache .
245,451
def _disable_module ( module ) : try : subprocess . check_call ( [ 'a2dismod' , module ] ) except subprocess . CalledProcessError as e : log ( 'Error occurred disabling module %s. ' 'Output is: %s' % ( module , e . output ) , level = ERROR )
Disables the specified module in Apache .
245,452
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 .
245,453
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 .
245,454
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 .
245,455
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 .
245,456
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 .
245,457
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 .
245,458
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
245,459
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 .
245,460
def _determine_branch_locations ( self , other_services ) : self . log . info ( 'OpenStackAmuletDeployment: determine branch locations' ) base_charms = { 'mysql' : [ 'trusty' ] , 'mongodb' : [ 'trusty' ] , 'nrpe' : [ 'trusty' , 'xenial' ] , } for svc in other_services : if svc . get ( 'location' ) : continue if svc [ ...
Determine the branch locations for the other services .
245,461
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 .
245,462
def _get_openstack_release ( self ) : 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' , 'cloud:trusty-liberty' ) : self . trusty_liberty , ( 'trusty...
Get openstack release .
245,463
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 .
245,464
def get_ceph_expected_pools ( self , radosgw = False ) : if self . _get_openstack_release ( ) == self . trusty_icehouse : pools = [ 'data' , 'metadata' , 'rbd' , 'cinder-ceph' , 'glance' ] elif ( self . trusty_kilo <= self . _get_openstack_release ( ) <= self . zesty_ocata ) : pools = [ 'rbd' , 'cinder-ceph' , 'glance'...
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 .
245,465
def get_platform ( ) : tuple_platform = platform . linux_distribution ( ) current_platform = tuple_platform [ 0 ] if "Ubuntu" in current_platform : return "ubuntu" elif "CentOS" in current_platform : return "centos" elif "debian" in current_platform : return "ubuntu" else : raise RuntimeError ( "This module is not supp...
Return the current OS platform .
245,466
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
245,467
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 .
245,468
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 .
245,469
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 . p...
Pause a system service .
245,470
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 ( 'enab...
Resume a system service .
245,471
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 .
245,472
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 , value...
Determine whether a system service is running .
245,473
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 .
245,474
def user_exists ( username ) : try : pwd . getpwnam ( username ) user_exists = True except KeyError : user_exists = False return user_exists
Check if a user exists
245,475
def uid_exists ( uid ) : try : pwd . getpwuid ( uid ) uid_exists = True except KeyError : uid_exists = False return uid_exists
Check if a uid exists
245,476
def group_exists ( groupname ) : try : grp . getgrnam ( groupname ) group_exists = True except KeyError : group_exists = False return group_exists
Check if a group exists
245,477
def gid_exists ( gid ) : try : grp . getgrgid ( gid ) gid_exists = True except KeyError : gid_exists = False return gid_exists
Check if a gid exists
245,478
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
245,479
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
245,480
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
245,481
def write_file ( path , content , owner = 'root' , group = 'root' , perms = 0o444 ) : uid = pwd . getpwnam ( owner ) . pw_uid gid = grp . getgrnam ( group ) . gr_gid existing_content = None existing_uid , existing_gid , existing_perms = None , None , None try : with open ( path , 'rb' ) as target : existing_content = t...
Create or overwrite a file with the contents of a byte string .
245,482
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
245,483
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
245,484
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
245,485
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 .
245,486
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 .
245,487
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
245,488
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 ( ) restarts = [ restart_map [ path ] for path in restart_map if path_hash ( path...
Helper function to perform the restart_on_change function .
245,489
def pwgen ( length = None ) : if length is None : length = random . choice ( range ( 35 , 45 ) ) alphanumeric_chars = [ l for l in ( string . ascii_letters + string . digits ) if l not in 'l0QD1vAEIOUaeiou' ] random_generator = random . SystemRandom ( ) random_chars = [ random_generator . choice ( alphanumeric_chars ) ...
Generate a random pasword .
245,490
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 .
245,491
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 .
245,492
def chdir ( directory ) : cur = os . getcwd ( ) try : yield os . chdir ( directory ) finally : os . chdir ( cur )
Change the current working directory to a different directory for a code block and return the previous directory after the block exits . Useful to run commands from a specificed directory .
245,493
def chownr ( path , owner , group , follow_links = True , chowntopdir = False ) : uid = pwd . getpwnam ( owner ) . pw_uid gid = grp . getgrnam ( group ) . gr_gid if follow_links : chown = os . chown else : chown = os . lchown if chowntopdir : broken_symlink = os . path . lexists ( path ) and not os . path . exists ( pa...
Recursively change user and group ownership of files and directories in given path . Doesn t chown path itself by default only its children .
245,494
def lchownr ( path , owner , group ) : chownr ( path , owner , group , follow_links = False )
Recursively change user and group ownership of files and directories in a given path not following symbolic links . See the documentation for os . lchown for more information .
245,495
def owner ( path ) : stat = os . stat ( path ) username = pwd . getpwuid ( stat . st_uid ) [ 0 ] groupname = grp . getgrgid ( stat . st_gid ) [ 0 ] return username , groupname
Returns a tuple containing the username & groupname owning the path .
245,496
def get_total_ram ( ) : with open ( '/proc/meminfo' , 'r' ) as f : for line in f . readlines ( ) : if line : key , value , unit = line . split ( ) if key == 'MemTotal:' : assert unit == 'kB' , 'Unknown unit' return int ( value ) * 1024 raise NotImplementedError ( )
The total amount of system RAM in bytes .
245,497
def add_to_updatedb_prunepath ( path , updatedb_path = UPDATEDB_PATH ) : if not os . path . exists ( updatedb_path ) or os . path . isdir ( updatedb_path ) : return with open ( updatedb_path , 'r+' ) as f_id : updatedb_text = f_id . read ( ) output = updatedb ( updatedb_text , path ) f_id . seek ( 0 ) f_id . write ( ou...
Adds the specified path to the mlocate s udpatedb . conf PRUNEPATH list .
245,498
def install_ca_cert ( ca_cert , name = None ) : if not ca_cert : return if not isinstance ( ca_cert , bytes ) : ca_cert = ca_cert . encode ( 'utf8' ) if not name : name = 'juju-{}' . format ( charm_name ( ) ) cert_file = '/usr/local/share/ca-certificates/{}.crt' . format ( name ) new_hash = hashlib . md5 ( ca_cert ) . ...
Install the given cert as a trusted CA .
245,499
def get_audits ( ) : audits = [ ] audits . append ( TemplatedFile ( '/etc/securetty' , SecureTTYContext ( ) , template_dir = TEMPLATES_DIR , mode = 0o0400 , user = 'root' , group = 'root' ) ) return audits
Get OS hardening Secure TTY audits .