repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.create_cirros_image
def create_cirros_image(self, glance, image_name, hypervisor_type=None): """Download the latest cirros image and upload it to glance, validate and return a resource pointer. :param glance: pointer to authenticated glance connection :param image_name: display name for new image :param hypervisor_type: glance image hypervisor property :returns: glance image pointer """ # /!\ 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 cirros image URL http_proxy = os.getenv('AMULET_HTTP_PROXY') self.log.debug('AMULET_HTTP_PROXY: {}'.format(http_proxy)) if http_proxy: proxies = {'http': http_proxy} opener = urllib.FancyURLopener(proxies) else: opener = urllib.FancyURLopener() f = opener.open('http://download.cirros-cloud.net/version/released') version = f.read().strip() cirros_img = 'cirros-{}-x86_64-disk.img'.format(version) cirros_url = 'http://{}/{}/{}'.format('download.cirros-cloud.net', version, cirros_img) f.close() return self.glance_create_image( glance, image_name, cirros_url, hypervisor_type=hypervisor_type)
python
def create_cirros_image(self, glance, image_name, hypervisor_type=None): """Download the latest cirros image and upload it to glance, validate and return a resource pointer. :param glance: pointer to authenticated glance connection :param image_name: display name for new image :param hypervisor_type: glance image hypervisor property :returns: glance image pointer """ # /!\ 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 cirros image URL http_proxy = os.getenv('AMULET_HTTP_PROXY') self.log.debug('AMULET_HTTP_PROXY: {}'.format(http_proxy)) if http_proxy: proxies = {'http': http_proxy} opener = urllib.FancyURLopener(proxies) else: opener = urllib.FancyURLopener() f = opener.open('http://download.cirros-cloud.net/version/released') version = f.read().strip() cirros_img = 'cirros-{}-x86_64-disk.img'.format(version) cirros_url = 'http://{}/{}/{}'.format('download.cirros-cloud.net', version, cirros_img) f.close() return self.glance_create_image( glance, image_name, cirros_url, hypervisor_type=hypervisor_type)
[ "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 cirros image URL", "http_proxy", "=", "os", ".", "getenv", "(", "'AMULET_HTTP_PROXY'", ")", "self", ".", "log", ".", "debug", "(", "'AMULET_HTTP_PROXY: {}'", ".", "format", "(", "http_proxy", ")", ")", "if", "http_proxy", ":", "proxies", "=", "{", "'http'", ":", "http_proxy", "}", "opener", "=", "urllib", ".", "FancyURLopener", "(", "proxies", ")", "else", ":", "opener", "=", "urllib", ".", "FancyURLopener", "(", ")", "f", "=", "opener", ".", "open", "(", "'http://download.cirros-cloud.net/version/released'", ")", "version", "=", "f", ".", "read", "(", ")", ".", "strip", "(", ")", "cirros_img", "=", "'cirros-{}-x86_64-disk.img'", ".", "format", "(", "version", ")", "cirros_url", "=", "'http://{}/{}/{}'", ".", "format", "(", "'download.cirros-cloud.net'", ",", "version", ",", "cirros_img", ")", "f", ".", "close", "(", ")", "return", "self", ".", "glance_create_image", "(", "glance", ",", "image_name", ",", "cirros_url", ",", "hypervisor_type", "=", "hypervisor_type", ")" ]
Download the latest cirros image and upload it to glance, validate and return a resource pointer. :param glance: pointer to authenticated glance connection :param image_name: display name for new image :param hypervisor_type: glance image hypervisor property :returns: glance image pointer
[ "Download", "the", "latest", "cirros", "image", "and", "upload", "it", "to", "glance", "validate", "and", "return", "a", "resource", "pointer", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L781-L818
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.delete_image
def delete_image(self, glance, image): """Delete the specified 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')
python
def delete_image(self, glance, image): """Delete the specified 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')
[ "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.
[ "Delete", "the", "specified", "image", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L820-L827
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.create_instance
def create_instance(self, nova, image_name, instance_name, flavor): """Create the specified instance.""" 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(name=instance_name, image=image, flavor=flavor) count = 1 status = instance.status while status != 'ACTIVE' and count < 60: time.sleep(3) instance = nova.servers.get(instance.id) status = instance.status self.log.debug('instance status: {}'.format(status)) count += 1 if status != 'ACTIVE': self.log.error('instance creation timed out') return None return instance
python
def create_instance(self, nova, image_name, instance_name, flavor): """Create the specified instance.""" 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(name=instance_name, image=image, flavor=flavor) count = 1 status = instance.status while status != 'ACTIVE' and count < 60: time.sleep(3) instance = nova.servers.get(instance.id) status = instance.status self.log.debug('instance status: {}'.format(status)) count += 1 if status != 'ACTIVE': self.log.error('instance creation timed out') return None return instance
[ "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", "(", "name", "=", "instance_name", ",", "image", "=", "image", ",", "flavor", "=", "flavor", ")", "count", "=", "1", "status", "=", "instance", ".", "status", "while", "status", "!=", "'ACTIVE'", "and", "count", "<", "60", ":", "time", ".", "sleep", "(", "3", ")", "instance", "=", "nova", ".", "servers", ".", "get", "(", "instance", ".", "id", ")", "status", "=", "instance", ".", "status", "self", ".", "log", ".", "debug", "(", "'instance status: {}'", ".", "format", "(", "status", ")", ")", "count", "+=", "1", "if", "status", "!=", "'ACTIVE'", ":", "self", ".", "log", ".", "error", "(", "'instance creation timed out'", ")", "return", "None", "return", "instance" ]
Create the specified instance.
[ "Create", "the", "specified", "instance", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L829-L851
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.delete_instance
def delete_instance(self, nova, instance): """Delete the specified 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 instance')
python
def delete_instance(self, nova, instance): """Delete the specified 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 instance')
[ "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 instance'", ")" ]
Delete the specified instance.
[ "Delete", "the", "specified", "instance", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L853-L861
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.create_or_get_keypair
def create_or_get_keypair(self, nova, keypair_name="testkey"): """Create a new keypair, or return pointer if it already exists.""" 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.'.format(keypair_name)) _keypair = nova.keypairs.create(name=keypair_name) return _keypair
python
def create_or_get_keypair(self, nova, keypair_name="testkey"): """Create a new keypair, or return pointer if it already exists.""" 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.'.format(keypair_name)) _keypair = nova.keypairs.create(name=keypair_name) return _keypair
[ "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.'", ".", "format", "(", "keypair_name", ")", ")", "_keypair", "=", "nova", ".", "keypairs", ".", "create", "(", "name", "=", "keypair_name", ")", "return", "_keypair" ]
Create a new keypair, or return pointer if it already exists.
[ "Create", "a", "new", "keypair", "or", "return", "pointer", "if", "it", "already", "exists", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L863-L875
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.create_cinder_volume
def create_cinder_volume(self, cinder, vol_name="demo-vol", vol_size=1, img_id=None, src_vol_id=None, snap_id=None): """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. :param vol_name: cinder volume display name :param vol_size: size in gigabytes :param img_id: optional glance image id :param src_vol_id: optional source volume id to clone :param snap_id: optional snapshot id to use :returns: cinder volume pointer """ # Handle parameter input and avoid impossible combinations if img_id and not src_vol_id and not snap_id: # Create volume from image self.log.debug('Creating cinder volume from glance image...') bootable = 'true' elif src_vol_id and not img_id and not snap_id: # Clone an existing volume self.log.debug('Cloning cinder volume...') bootable = cinder.volumes.get(src_vol_id).bootable elif snap_id and not src_vol_id and not img_id: # Create volume from snapshot self.log.debug('Creating cinder volume from snapshot...') snap = cinder.volume_snapshots.find(id=snap_id) vol_size = snap.size snap_vol_id = cinder.volume_snapshots.get(snap_id).volume_id bootable = cinder.volumes.get(snap_vol_id).bootable elif not img_id and not src_vol_id and not snap_id: # Create volume self.log.debug('Creating cinder volume...') bootable = 'false' else: # Impossible combination of parameters msg = ('Invalid method use - name:{} size:{} img_id:{} ' 'src_vol_id:{} snap_id:{}'.format(vol_name, vol_size, img_id, src_vol_id, snap_id)) amulet.raise_status(amulet.FAIL, msg=msg) # Create new volume try: vol_new = cinder.volumes.create(display_name=vol_name, imageRef=img_id, size=vol_size, source_volid=src_vol_id, snapshot_id=snap_id) vol_id = vol_new.id except TypeError: vol_new = cinder.volumes.create(name=vol_name, imageRef=img_id, size=vol_size, source_volid=src_vol_id, snapshot_id=snap_id) vol_id = vol_new.id except Exception as e: msg = 'Failed to create volume: {}'.format(e) amulet.raise_status(amulet.FAIL, msg=msg) # Wait for volume to reach available status ret = self.resource_reaches_status(cinder.volumes, vol_id, expected_stat="available", msg="Volume status wait") if not ret: msg = 'Cinder volume failed to reach expected state.' amulet.raise_status(amulet.FAIL, msg=msg) # Re-validate new volume self.log.debug('Validating volume attributes...') val_vol_name = self._get_cinder_obj_name(cinder.volumes.get(vol_id)) val_vol_boot = cinder.volumes.get(vol_id).bootable val_vol_stat = cinder.volumes.get(vol_id).status val_vol_size = cinder.volumes.get(vol_id).size msg_attr = ('Volume attributes - name:{} id:{} stat:{} boot:' '{} size:{}'.format(val_vol_name, vol_id, val_vol_stat, val_vol_boot, val_vol_size)) if val_vol_boot == bootable and val_vol_stat == 'available' \ and val_vol_name == vol_name and val_vol_size == vol_size: self.log.debug(msg_attr) else: msg = ('Volume validation failed, {}'.format(msg_attr)) amulet.raise_status(amulet.FAIL, msg=msg) return vol_new
python
def create_cinder_volume(self, cinder, vol_name="demo-vol", vol_size=1, img_id=None, src_vol_id=None, snap_id=None): """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. :param vol_name: cinder volume display name :param vol_size: size in gigabytes :param img_id: optional glance image id :param src_vol_id: optional source volume id to clone :param snap_id: optional snapshot id to use :returns: cinder volume pointer """ # Handle parameter input and avoid impossible combinations if img_id and not src_vol_id and not snap_id: # Create volume from image self.log.debug('Creating cinder volume from glance image...') bootable = 'true' elif src_vol_id and not img_id and not snap_id: # Clone an existing volume self.log.debug('Cloning cinder volume...') bootable = cinder.volumes.get(src_vol_id).bootable elif snap_id and not src_vol_id and not img_id: # Create volume from snapshot self.log.debug('Creating cinder volume from snapshot...') snap = cinder.volume_snapshots.find(id=snap_id) vol_size = snap.size snap_vol_id = cinder.volume_snapshots.get(snap_id).volume_id bootable = cinder.volumes.get(snap_vol_id).bootable elif not img_id and not src_vol_id and not snap_id: # Create volume self.log.debug('Creating cinder volume...') bootable = 'false' else: # Impossible combination of parameters msg = ('Invalid method use - name:{} size:{} img_id:{} ' 'src_vol_id:{} snap_id:{}'.format(vol_name, vol_size, img_id, src_vol_id, snap_id)) amulet.raise_status(amulet.FAIL, msg=msg) # Create new volume try: vol_new = cinder.volumes.create(display_name=vol_name, imageRef=img_id, size=vol_size, source_volid=src_vol_id, snapshot_id=snap_id) vol_id = vol_new.id except TypeError: vol_new = cinder.volumes.create(name=vol_name, imageRef=img_id, size=vol_size, source_volid=src_vol_id, snapshot_id=snap_id) vol_id = vol_new.id except Exception as e: msg = 'Failed to create volume: {}'.format(e) amulet.raise_status(amulet.FAIL, msg=msg) # Wait for volume to reach available status ret = self.resource_reaches_status(cinder.volumes, vol_id, expected_stat="available", msg="Volume status wait") if not ret: msg = 'Cinder volume failed to reach expected state.' amulet.raise_status(amulet.FAIL, msg=msg) # Re-validate new volume self.log.debug('Validating volume attributes...') val_vol_name = self._get_cinder_obj_name(cinder.volumes.get(vol_id)) val_vol_boot = cinder.volumes.get(vol_id).bootable val_vol_stat = cinder.volumes.get(vol_id).status val_vol_size = cinder.volumes.get(vol_id).size msg_attr = ('Volume attributes - name:{} id:{} stat:{} boot:' '{} size:{}'.format(val_vol_name, vol_id, val_vol_stat, val_vol_boot, val_vol_size)) if val_vol_boot == bootable and val_vol_stat == 'available' \ and val_vol_name == vol_name and val_vol_size == vol_size: self.log.debug(msg_attr) else: msg = ('Volume validation failed, {}'.format(msg_attr)) amulet.raise_status(amulet.FAIL, msg=msg) return vol_new
[ "def", "create_cinder_volume", "(", "self", ",", "cinder", ",", "vol_name", "=", "\"demo-vol\"", ",", "vol_size", "=", "1", ",", "img_id", "=", "None", ",", "src_vol_id", "=", "None", ",", "snap_id", "=", "None", ")", ":", "# Handle parameter input and avoid impossible combinations", "if", "img_id", "and", "not", "src_vol_id", "and", "not", "snap_id", ":", "# Create volume from image", "self", ".", "log", ".", "debug", "(", "'Creating cinder volume from glance image...'", ")", "bootable", "=", "'true'", "elif", "src_vol_id", "and", "not", "img_id", "and", "not", "snap_id", ":", "# Clone an existing volume", "self", ".", "log", ".", "debug", "(", "'Cloning cinder volume...'", ")", "bootable", "=", "cinder", ".", "volumes", ".", "get", "(", "src_vol_id", ")", ".", "bootable", "elif", "snap_id", "and", "not", "src_vol_id", "and", "not", "img_id", ":", "# Create volume from snapshot", "self", ".", "log", ".", "debug", "(", "'Creating cinder volume from snapshot...'", ")", "snap", "=", "cinder", ".", "volume_snapshots", ".", "find", "(", "id", "=", "snap_id", ")", "vol_size", "=", "snap", ".", "size", "snap_vol_id", "=", "cinder", ".", "volume_snapshots", ".", "get", "(", "snap_id", ")", ".", "volume_id", "bootable", "=", "cinder", ".", "volumes", ".", "get", "(", "snap_vol_id", ")", ".", "bootable", "elif", "not", "img_id", "and", "not", "src_vol_id", "and", "not", "snap_id", ":", "# Create volume", "self", ".", "log", ".", "debug", "(", "'Creating cinder volume...'", ")", "bootable", "=", "'false'", "else", ":", "# Impossible combination of parameters", "msg", "=", "(", "'Invalid method use - name:{} size:{} img_id:{} '", "'src_vol_id:{} snap_id:{}'", ".", "format", "(", "vol_name", ",", "vol_size", ",", "img_id", ",", "src_vol_id", ",", "snap_id", ")", ")", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "msg", ")", "# Create new volume", "try", ":", "vol_new", "=", "cinder", ".", "volumes", ".", "create", "(", "display_name", "=", "vol_name", ",", "imageRef", "=", "img_id", ",", "size", "=", "vol_size", ",", "source_volid", "=", "src_vol_id", ",", "snapshot_id", "=", "snap_id", ")", "vol_id", "=", "vol_new", ".", "id", "except", "TypeError", ":", "vol_new", "=", "cinder", ".", "volumes", ".", "create", "(", "name", "=", "vol_name", ",", "imageRef", "=", "img_id", ",", "size", "=", "vol_size", ",", "source_volid", "=", "src_vol_id", ",", "snapshot_id", "=", "snap_id", ")", "vol_id", "=", "vol_new", ".", "id", "except", "Exception", "as", "e", ":", "msg", "=", "'Failed to create volume: {}'", ".", "format", "(", "e", ")", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "msg", ")", "# Wait for volume to reach available status", "ret", "=", "self", ".", "resource_reaches_status", "(", "cinder", ".", "volumes", ",", "vol_id", ",", "expected_stat", "=", "\"available\"", ",", "msg", "=", "\"Volume status wait\"", ")", "if", "not", "ret", ":", "msg", "=", "'Cinder volume failed to reach expected state.'", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "msg", ")", "# Re-validate new volume", "self", ".", "log", ".", "debug", "(", "'Validating volume attributes...'", ")", "val_vol_name", "=", "self", ".", "_get_cinder_obj_name", "(", "cinder", ".", "volumes", ".", "get", "(", "vol_id", ")", ")", "val_vol_boot", "=", "cinder", ".", "volumes", ".", "get", "(", "vol_id", ")", ".", "bootable", "val_vol_stat", "=", "cinder", ".", "volumes", ".", "get", "(", "vol_id", ")", ".", "status", "val_vol_size", "=", "cinder", ".", "volumes", ".", "get", "(", "vol_id", ")", ".", "size", "msg_attr", "=", "(", "'Volume attributes - name:{} id:{} stat:{} boot:'", "'{} size:{}'", ".", "format", "(", "val_vol_name", ",", "vol_id", ",", "val_vol_stat", ",", "val_vol_boot", ",", "val_vol_size", ")", ")", "if", "val_vol_boot", "==", "bootable", "and", "val_vol_stat", "==", "'available'", "and", "val_vol_name", "==", "vol_name", "and", "val_vol_size", "==", "vol_size", ":", "self", ".", "log", ".", "debug", "(", "msg_attr", ")", "else", ":", "msg", "=", "(", "'Volume validation failed, {}'", ".", "format", "(", "msg_attr", ")", ")", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "msg", ")", "return", "vol_new" ]
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. :param vol_name: cinder volume display name :param vol_size: size in gigabytes :param img_id: optional glance image id :param src_vol_id: optional source volume id to clone :param snap_id: optional snapshot id to use :returns: cinder volume pointer
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L889-L976
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.delete_resource
def delete_resource(self, resource, resource_id, msg="resource", max_wait=120): """Delete one openstack resource, such as one instance, keypair, image, volume, stack, etc., and confirm deletion within max wait time. :param resource: pointer to os resource type, ex:glance_client.images :param resource_id: unique name or id for the openstack resource :param msg: text to identify purpose in logging :param max_wait: maximum wait time in seconds :returns: True if successful, otherwise False """ 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.list())) while num_after != (num_before - 1) and tries < (max_wait / 4): self.log.debug('{} delete check: ' '{} [{}:{}] {}'.format(msg, tries, num_before, num_after, resource_id)) time.sleep(4) num_after = len(list(resource.list())) tries += 1 self.log.debug('{}: expected, actual count = {}, ' '{}'.format(msg, num_before - 1, num_after)) if num_after == (num_before - 1): return True else: self.log.error('{} delete timed out'.format(msg)) return False
python
def delete_resource(self, resource, resource_id, msg="resource", max_wait=120): """Delete one openstack resource, such as one instance, keypair, image, volume, stack, etc., and confirm deletion within max wait time. :param resource: pointer to os resource type, ex:glance_client.images :param resource_id: unique name or id for the openstack resource :param msg: text to identify purpose in logging :param max_wait: maximum wait time in seconds :returns: True if successful, otherwise False """ 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.list())) while num_after != (num_before - 1) and tries < (max_wait / 4): self.log.debug('{} delete check: ' '{} [{}:{}] {}'.format(msg, tries, num_before, num_after, resource_id)) time.sleep(4) num_after = len(list(resource.list())) tries += 1 self.log.debug('{}: expected, actual count = {}, ' '{}'.format(msg, num_before - 1, num_after)) if num_after == (num_before - 1): return True else: self.log.error('{} delete timed out'.format(msg)) return False
[ "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", ".", "list", "(", ")", ")", ")", "while", "num_after", "!=", "(", "num_before", "-", "1", ")", "and", "tries", "<", "(", "max_wait", "/", "4", ")", ":", "self", ".", "log", ".", "debug", "(", "'{} delete check: '", "'{} [{}:{}] {}'", ".", "format", "(", "msg", ",", "tries", ",", "num_before", ",", "num_after", ",", "resource_id", ")", ")", "time", ".", "sleep", "(", "4", ")", "num_after", "=", "len", "(", "list", "(", "resource", ".", "list", "(", ")", ")", ")", "tries", "+=", "1", "self", ".", "log", ".", "debug", "(", "'{}: expected, actual count = {}, '", "'{}'", ".", "format", "(", "msg", ",", "num_before", "-", "1", ",", "num_after", ")", ")", "if", "num_after", "==", "(", "num_before", "-", "1", ")", ":", "return", "True", "else", ":", "self", ".", "log", ".", "error", "(", "'{} delete timed out'", ".", "format", "(", "msg", ")", ")", "return", "False" ]
Delete one openstack resource, such as one instance, keypair, image, volume, stack, etc., and confirm deletion within max wait time. :param resource: pointer to os resource type, ex:glance_client.images :param resource_id: unique name or id for the openstack resource :param msg: text to identify purpose in logging :param max_wait: maximum wait time in seconds :returns: True if successful, otherwise False
[ "Delete", "one", "openstack", "resource", "such", "as", "one", "instance", "keypair", "image", "volume", "stack", "etc", ".", "and", "confirm", "deletion", "within", "max", "wait", "time", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L978-L1013
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.resource_reaches_status
def resource_reaches_status(self, resource, resource_id, expected_stat='available', msg='resource', max_wait=120): """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. :param resource: pointer to os resource type, ex: heat_client.stacks :param resource_id: unique id for the openstack resource :param expected_stat: status to expect resource to reach :param msg: text to identify purpose in logging :param max_wait: maximum wait time in seconds :returns: True if successful, False if status is not reached """ tries = 0 resource_stat = resource.get(resource_id).status while resource_stat != expected_stat and tries < (max_wait / 4): self.log.debug('{} status check: ' '{} [{}:{}] {}'.format(msg, tries, resource_stat, expected_stat, resource_id)) time.sleep(4) resource_stat = resource.get(resource_id).status tries += 1 self.log.debug('{}: expected, actual status = {}, ' '{}'.format(msg, resource_stat, expected_stat)) if resource_stat == expected_stat: return True else: self.log.debug('{} never reached expected status: ' '{}'.format(resource_id, expected_stat)) return False
python
def resource_reaches_status(self, resource, resource_id, expected_stat='available', msg='resource', max_wait=120): """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. :param resource: pointer to os resource type, ex: heat_client.stacks :param resource_id: unique id for the openstack resource :param expected_stat: status to expect resource to reach :param msg: text to identify purpose in logging :param max_wait: maximum wait time in seconds :returns: True if successful, False if status is not reached """ tries = 0 resource_stat = resource.get(resource_id).status while resource_stat != expected_stat and tries < (max_wait / 4): self.log.debug('{} status check: ' '{} [{}:{}] {}'.format(msg, tries, resource_stat, expected_stat, resource_id)) time.sleep(4) resource_stat = resource.get(resource_id).status tries += 1 self.log.debug('{}: expected, actual status = {}, ' '{}'.format(msg, resource_stat, expected_stat)) if resource_stat == expected_stat: return True else: self.log.debug('{} never reached expected status: ' '{}'.format(resource_id, expected_stat)) return False
[ "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: '", "'{} [{}:{}] {}'", ".", "format", "(", "msg", ",", "tries", ",", "resource_stat", ",", "expected_stat", ",", "resource_id", ")", ")", "time", ".", "sleep", "(", "4", ")", "resource_stat", "=", "resource", ".", "get", "(", "resource_id", ")", ".", "status", "tries", "+=", "1", "self", ".", "log", ".", "debug", "(", "'{}: expected, actual status = {}, '", "'{}'", ".", "format", "(", "msg", ",", "resource_stat", ",", "expected_stat", ")", ")", "if", "resource_stat", "==", "expected_stat", ":", "return", "True", "else", ":", "self", ".", "log", ".", "debug", "(", "'{} never reached expected status: '", "'{}'", ".", "format", "(", "resource_id", ",", "expected_stat", ")", ")", "return", "False" ]
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. :param resource: pointer to os resource type, ex: heat_client.stacks :param resource_id: unique id for the openstack resource :param expected_stat: status to expect resource to reach :param msg: text to identify purpose in logging :param max_wait: maximum wait time in seconds :returns: True if successful, False if status is not reached
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1015-L1051
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.get_ceph_pools
def get_ceph_pools(self, sentry_unit): """Return a dict of ceph pools from a single ceph unit, with pool name as keys, pool id as vals.""" 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 osd lspools output output = output.replace("\n", ",") # Example output: 0 data,1 metadata,2 rbd,3 cinder,4 glance, for pool in str(output).split(','): pool_id_name = pool.split(' ') if len(pool_id_name) == 2: pool_id = pool_id_name[0] pool_name = pool_id_name[1] pools[pool_name] = int(pool_id) self.log.debug('Pools on {}: {}'.format(sentry_unit.info['unit_name'], pools)) return pools
python
def get_ceph_pools(self, sentry_unit): """Return a dict of ceph pools from a single ceph unit, with pool name as keys, pool id as vals.""" 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 osd lspools output output = output.replace("\n", ",") # Example output: 0 data,1 metadata,2 rbd,3 cinder,4 glance, for pool in str(output).split(','): pool_id_name = pool.split(' ') if len(pool_id_name) == 2: pool_id = pool_id_name[0] pool_name = pool_id_name[1] pools[pool_name] = int(pool_id) self.log.debug('Pools on {}: {}'.format(sentry_unit.info['unit_name'], pools)) return pools
[ "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 osd lspools output", "output", "=", "output", ".", "replace", "(", "\"\\n\"", ",", "\",\"", ")", "# Example output: 0 data,1 metadata,2 rbd,3 cinder,4 glance,", "for", "pool", "in", "str", "(", "output", ")", ".", "split", "(", "','", ")", ":", "pool_id_name", "=", "pool", ".", "split", "(", "' '", ")", "if", "len", "(", "pool_id_name", ")", "==", "2", ":", "pool_id", "=", "pool_id_name", "[", "0", "]", "pool_name", "=", "pool_id_name", "[", "1", "]", "pools", "[", "pool_name", "]", "=", "int", "(", "pool_id", ")", "self", ".", "log", ".", "debug", "(", "'Pools on {}: {}'", ".", "format", "(", "sentry_unit", ".", "info", "[", "'unit_name'", "]", ",", "pools", ")", ")", "return", "pools" ]
Return a dict of ceph pools from a single ceph unit, with pool name as keys, pool id as vals.
[ "Return", "a", "dict", "of", "ceph", "pools", "from", "a", "single", "ceph", "unit", "with", "pool", "name", "as", "keys", "pool", "id", "as", "vals", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1059-L1084
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.get_ceph_df
def get_ceph_df(self, sentry_unit): """Return dict of ceph df json output, including ceph pool state. :param sentry_unit: Pointer to amulet sentry instance (juju unit) :returns: Dict of ceph df output """ 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(output)
python
def get_ceph_df(self, sentry_unit): """Return dict of ceph df json output, including ceph pool state. :param sentry_unit: Pointer to amulet sentry instance (juju unit) :returns: Dict of ceph df output """ 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(output)
[ "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", "(", "output", ")" ]
Return dict of ceph df json output, including ceph pool state. :param sentry_unit: Pointer to amulet sentry instance (juju unit) :returns: Dict of ceph df output
[ "Return", "dict", "of", "ceph", "df", "json", "output", "including", "ceph", "pool", "state", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1086-L1099
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.get_ceph_pool_sample
def get_ceph_pool_sample(self, sentry_unit, pool_id=0): """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. :param sentry_unit: Pointer to amulet sentry instance (juju unit) :param pool_id: Ceph pool ID :returns: List of pool name, object count, kb disk space used """ 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 {}): {} objects, ' '{} kb used'.format(pool_name, pool_id, obj_count, kb_used)) return pool_name, obj_count, kb_used
python
def get_ceph_pool_sample(self, sentry_unit, pool_id=0): """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. :param sentry_unit: Pointer to amulet sentry instance (juju unit) :param pool_id: Ceph pool ID :returns: List of pool name, object count, kb disk space used """ 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 {}): {} objects, ' '{} kb used'.format(pool_name, pool_id, obj_count, kb_used)) return pool_name, obj_count, kb_used
[ "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 {}): {} objects, '", "'{} kb used'", ".", "format", "(", "pool_name", ",", "pool_id", ",", "obj_count", ",", "kb_used", ")", ")", "return", "pool_name", ",", "obj_count", ",", "kb_used" ]
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. :param sentry_unit: Pointer to amulet sentry instance (juju unit) :param pool_id: Ceph pool ID :returns: List of pool name, object count, kb disk space used
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1101-L1120
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_ceph_pool_samples
def validate_ceph_pool_samples(self, samples, sample_type="resource pool"): """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. :param samples: List containing 3 data samples :param sample_type: String for logging and usage context :returns: None if successful, Failure message otherwise """ 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.log.debug('Ceph {} samples (OK): ' '{}'.format(sample_type, samples)) return None
python
def validate_ceph_pool_samples(self, samples, sample_type="resource pool"): """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. :param samples: List containing 3 data samples :param sample_type: String for logging and usage context :returns: None if successful, Failure message otherwise """ 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.log.debug('Ceph {} samples (OK): ' '{}'.format(sample_type, samples)) return None
[ "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", ".", "log", ".", "debug", "(", "'Ceph {} samples (OK): '", "'{}'", ".", "format", "(", "sample_type", ",", "samples", ")", ")", "return", "None" ]
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. :param samples: List containing 3 data samples :param sample_type: String for logging and usage context :returns: None if successful, Failure message otherwise
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1122-L1141
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.rmq_wait_for_cluster
def rmq_wait_for_cluster(self, deployment, init_sleep=15, timeout=1200): """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.""" 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'])
python
def rmq_wait_for_cluster(self, deployment, init_sleep=15, timeout=1200): """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.""" 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'])
[ "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.
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1145-L1157
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.get_rmq_cluster_status
def get_rmq_cluster_status(self, sentry_unit): """Execute rabbitmq cluster status command on a unit and return the full output. :param unit: sentry unit :returns: String containing console output of cluster status command """ 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)
python
def get_rmq_cluster_status(self, sentry_unit): """Execute rabbitmq cluster status command on a unit and return the full output. :param unit: sentry unit :returns: String containing console output of cluster status command """ 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)
[ "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. :param unit: sentry unit :returns: String containing console output of cluster status command
[ "Execute", "rabbitmq", "cluster", "status", "command", "on", "a", "unit", "and", "return", "the", "full", "output", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1218-L1229
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.get_rmq_cluster_running_nodes
def get_rmq_cluster_running_nodes(self, sentry_unit): """Parse rabbitmqctl cluster_status output string, return list of running rabbitmq cluster nodes. :param unit: sentry unit :returns: List containing node names of running nodes """ # 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 pos_end = str_stat.find("]},", pos_start) + 1 str_run_nodes = str_stat[pos_start:pos_end].replace("'", '"') run_nodes = json.loads(str_run_nodes) return run_nodes else: return []
python
def get_rmq_cluster_running_nodes(self, sentry_unit): """Parse rabbitmqctl cluster_status output string, return list of running rabbitmq cluster nodes. :param unit: sentry unit :returns: List containing node names of running nodes """ # 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 pos_end = str_stat.find("]},", pos_start) + 1 str_run_nodes = str_stat[pos_start:pos_end].replace("'", '"') run_nodes = json.loads(str_run_nodes) return run_nodes else: return []
[ "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", "pos_end", "=", "str_stat", ".", "find", "(", "\"]},\"", ",", "pos_start", ")", "+", "1", "str_run_nodes", "=", "str_stat", "[", "pos_start", ":", "pos_end", "]", ".", "replace", "(", "\"'\"", ",", "'\"'", ")", "run_nodes", "=", "json", ".", "loads", "(", "str_run_nodes", ")", "return", "run_nodes", "else", ":", "return", "[", "]" ]
Parse rabbitmqctl cluster_status output string, return list of running rabbitmq cluster nodes. :param unit: sentry unit :returns: List containing node names of running nodes
[ "Parse", "rabbitmqctl", "cluster_status", "output", "string", "return", "list", "of", "running", "rabbitmq", "cluster", "nodes", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1231-L1248
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_rmq_cluster_running_nodes
def validate_rmq_cluster_running_nodes(self, sentry_units): """Check that all rmq unit hostnames are represented in the cluster_status output of all units. :param host_names: dict of juju unit names to host names :param units: list of sentry unit pointers (all rmq units) :returns: None if successful, otherwise return error message """ 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_nodes(query_unit) # Confirm that every unit is represented in the queried unit's # cluster_status running nodes output. for validate_unit in sentry_units: val_host_name = host_names[validate_unit.info['unit_name']] val_node_name = 'rabbit@{}'.format(val_host_name) if val_node_name not in running_nodes: errors.append('Cluster member check failed on {}: {} not ' 'in {}\n'.format(query_unit_name, val_node_name, running_nodes)) if errors: return ''.join(errors)
python
def validate_rmq_cluster_running_nodes(self, sentry_units): """Check that all rmq unit hostnames are represented in the cluster_status output of all units. :param host_names: dict of juju unit names to host names :param units: list of sentry unit pointers (all rmq units) :returns: None if successful, otherwise return error message """ 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_nodes(query_unit) # Confirm that every unit is represented in the queried unit's # cluster_status running nodes output. for validate_unit in sentry_units: val_host_name = host_names[validate_unit.info['unit_name']] val_node_name = 'rabbit@{}'.format(val_host_name) if val_node_name not in running_nodes: errors.append('Cluster member check failed on {}: {} not ' 'in {}\n'.format(query_unit_name, val_node_name, running_nodes)) if errors: return ''.join(errors)
[ "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_nodes", "(", "query_unit", ")", "# Confirm that every unit is represented in the queried unit's", "# cluster_status running nodes output.", "for", "validate_unit", "in", "sentry_units", ":", "val_host_name", "=", "host_names", "[", "validate_unit", ".", "info", "[", "'unit_name'", "]", "]", "val_node_name", "=", "'rabbit@{}'", ".", "format", "(", "val_host_name", ")", "if", "val_node_name", "not", "in", "running_nodes", ":", "errors", ".", "append", "(", "'Cluster member check failed on {}: {} not '", "'in {}\\n'", ".", "format", "(", "query_unit_name", ",", "val_node_name", ",", "running_nodes", ")", ")", "if", "errors", ":", "return", "''", ".", "join", "(", "errors", ")" ]
Check that all rmq unit hostnames are represented in the cluster_status output of all units. :param host_names: dict of juju unit names to host names :param units: list of sentry unit pointers (all rmq units) :returns: None if successful, otherwise return error message
[ "Check", "that", "all", "rmq", "unit", "hostnames", "are", "represented", "in", "the", "cluster_status", "output", "of", "all", "units", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1250-L1278
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.rmq_ssl_is_enabled_on_unit
def rmq_ssl_is_enabled_on_unit(self, sentry_unit, port=None): """Check a single juju rmq unit for ssl and port in the config file.""" 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 = 'ssl' in conf_contents conf_port = str(port) in conf_contents # Port explicitly checked in config if port and conf_port and conf_ssl: self.log.debug('SSL is enabled @{}:{} ' '({})'.format(host, port, unit_name)) return True elif port and not conf_port and conf_ssl: self.log.debug('SSL is enabled @{} but not on port {} ' '({})'.format(host, port, unit_name)) return False # Port not checked (useful when checking that ssl is disabled) elif not port and conf_ssl: self.log.debug('SSL is enabled @{}:{} ' '({})'.format(host, port, unit_name)) return True elif not conf_ssl: self.log.debug('SSL not enabled @{}:{} ' '({})'.format(host, port, unit_name)) return False else: msg = ('Unknown condition when checking SSL status @{}:{} ' '({})'.format(host, port, unit_name)) amulet.raise_status(amulet.FAIL, msg)
python
def rmq_ssl_is_enabled_on_unit(self, sentry_unit, port=None): """Check a single juju rmq unit for ssl and port in the config file.""" 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 = 'ssl' in conf_contents conf_port = str(port) in conf_contents # Port explicitly checked in config if port and conf_port and conf_ssl: self.log.debug('SSL is enabled @{}:{} ' '({})'.format(host, port, unit_name)) return True elif port and not conf_port and conf_ssl: self.log.debug('SSL is enabled @{} but not on port {} ' '({})'.format(host, port, unit_name)) return False # Port not checked (useful when checking that ssl is disabled) elif not port and conf_ssl: self.log.debug('SSL is enabled @{}:{} ' '({})'.format(host, port, unit_name)) return True elif not conf_ssl: self.log.debug('SSL not enabled @{}:{} ' '({})'.format(host, port, unit_name)) return False else: msg = ('Unknown condition when checking SSL status @{}:{} ' '({})'.format(host, port, unit_name)) amulet.raise_status(amulet.FAIL, msg)
[ "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", "=", "'ssl'", "in", "conf_contents", "conf_port", "=", "str", "(", "port", ")", "in", "conf_contents", "# Port explicitly checked in config", "if", "port", "and", "conf_port", "and", "conf_ssl", ":", "self", ".", "log", ".", "debug", "(", "'SSL is enabled @{}:{} '", "'({})'", ".", "format", "(", "host", ",", "port", ",", "unit_name", ")", ")", "return", "True", "elif", "port", "and", "not", "conf_port", "and", "conf_ssl", ":", "self", ".", "log", ".", "debug", "(", "'SSL is enabled @{} but not on port {} '", "'({})'", ".", "format", "(", "host", ",", "port", ",", "unit_name", ")", ")", "return", "False", "# Port not checked (useful when checking that ssl is disabled)", "elif", "not", "port", "and", "conf_ssl", ":", "self", ".", "log", ".", "debug", "(", "'SSL is enabled @{}:{} '", "'({})'", ".", "format", "(", "host", ",", "port", ",", "unit_name", ")", ")", "return", "True", "elif", "not", "conf_ssl", ":", "self", ".", "log", ".", "debug", "(", "'SSL not enabled @{}:{} '", "'({})'", ".", "format", "(", "host", ",", "port", ",", "unit_name", ")", ")", "return", "False", "else", ":", "msg", "=", "(", "'Unknown condition when checking SSL status @{}:{} '", "'({})'", ".", "format", "(", "host", ",", "port", ",", "unit_name", ")", ")", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", ")" ]
Check a single juju rmq unit for ssl and port in the config file.
[ "Check", "a", "single", "juju", "rmq", "unit", "for", "ssl", "and", "port", "in", "the", "config", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1280-L1313
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_rmq_ssl_enabled_units
def validate_rmq_ssl_enabled_units(self, sentry_units, port=None): """Check that ssl is enabled on rmq juju sentry units. :param sentry_units: list of all rmq sentry units :param port: optional ssl port override to validate :returns: None if successful, otherwise return error message """ 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
python
def validate_rmq_ssl_enabled_units(self, sentry_units, port=None): """Check that ssl is enabled on rmq juju sentry units. :param sentry_units: list of all rmq sentry units :param port: optional ssl port override to validate :returns: None if successful, otherwise return error message """ 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
[ "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. :param sentry_units: list of all rmq sentry units :param port: optional ssl port override to validate :returns: None if successful, otherwise return error message
[ "Check", "that", "ssl", "is", "enabled", "on", "rmq", "juju", "sentry", "units", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1315-L1326
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_rmq_ssl_disabled_units
def validate_rmq_ssl_disabled_units(self, sentry_units): """Check that ssl is enabled on listed rmq juju sentry units. :param sentry_units: list of all rmq sentry units :returns: True if successful. Raise on error. """ 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
python
def validate_rmq_ssl_disabled_units(self, sentry_units): """Check that ssl is enabled on listed rmq juju sentry units. :param sentry_units: list of all rmq sentry units :returns: True if successful. Raise on error. """ 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
[ "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. :param sentry_units: list of all rmq sentry units :returns: True if successful. Raise on error.
[ "Check", "that", "ssl", "is", "enabled", "on", "listed", "rmq", "juju", "sentry", "units", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1328-L1338
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.configure_rmq_ssl_on
def configure_rmq_ssl_on(self, sentry_units, deployment, port=None, max_wait=60): """Turn ssl charm config option on, with optional non-default ssl port specification. Confirm that it is enabled on every unit. :param sentry_units: list of sentry units :param deployment: amulet deployment object pointer :param port: amqp port, use defaults if None :param max_wait: maximum time to wait in seconds to confirm :returns: None if successful. Raise on error. """ 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 self.rmq_wait_for_cluster(deployment) # Confirm tries = 0 ret = self.validate_rmq_ssl_enabled_units(sentry_units, port=port) while ret and tries < (max_wait / 4): time.sleep(4) self.log.debug('Attempt {}: {}'.format(tries, ret)) ret = self.validate_rmq_ssl_enabled_units(sentry_units, port=port) tries += 1 if ret: amulet.raise_status(amulet.FAIL, ret)
python
def configure_rmq_ssl_on(self, sentry_units, deployment, port=None, max_wait=60): """Turn ssl charm config option on, with optional non-default ssl port specification. Confirm that it is enabled on every unit. :param sentry_units: list of sentry units :param deployment: amulet deployment object pointer :param port: amqp port, use defaults if None :param max_wait: maximum time to wait in seconds to confirm :returns: None if successful. Raise on error. """ 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 self.rmq_wait_for_cluster(deployment) # Confirm tries = 0 ret = self.validate_rmq_ssl_enabled_units(sentry_units, port=port) while ret and tries < (max_wait / 4): time.sleep(4) self.log.debug('Attempt {}: {}'.format(tries, ret)) ret = self.validate_rmq_ssl_enabled_units(sentry_units, port=port) tries += 1 if ret: amulet.raise_status(amulet.FAIL, ret)
[ "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", "self", ".", "rmq_wait_for_cluster", "(", "deployment", ")", "# Confirm", "tries", "=", "0", "ret", "=", "self", ".", "validate_rmq_ssl_enabled_units", "(", "sentry_units", ",", "port", "=", "port", ")", "while", "ret", "and", "tries", "<", "(", "max_wait", "/", "4", ")", ":", "time", ".", "sleep", "(", "4", ")", "self", ".", "log", ".", "debug", "(", "'Attempt {}: {}'", ".", "format", "(", "tries", ",", "ret", ")", ")", "ret", "=", "self", ".", "validate_rmq_ssl_enabled_units", "(", "sentry_units", ",", "port", "=", "port", ")", "tries", "+=", "1", "if", "ret", ":", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "ret", ")" ]
Turn ssl charm config option on, with optional non-default ssl port specification. Confirm that it is enabled on every unit. :param sentry_units: list of sentry units :param deployment: amulet deployment object pointer :param port: amqp port, use defaults if None :param max_wait: maximum time to wait in seconds to confirm :returns: None if successful. Raise on error.
[ "Turn", "ssl", "charm", "config", "option", "on", "with", "optional", "non", "-", "default", "ssl", "port", "specification", ".", "Confirm", "that", "it", "is", "enabled", "on", "every", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1340-L1374
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.configure_rmq_ssl_off
def configure_rmq_ssl_off(self, sentry_units, deployment, max_wait=60): """Turn ssl charm config option off, confirm that it is disabled on every unit. :param sentry_units: list of sentry units :param deployment: amulet deployment object pointer :param max_wait: maximum time to wait in seconds to confirm :returns: None if successful. Raise on error. """ 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) # Confirm tries = 0 ret = self.validate_rmq_ssl_disabled_units(sentry_units) while ret and tries < (max_wait / 4): time.sleep(4) self.log.debug('Attempt {}: {}'.format(tries, ret)) ret = self.validate_rmq_ssl_disabled_units(sentry_units) tries += 1 if ret: amulet.raise_status(amulet.FAIL, ret)
python
def configure_rmq_ssl_off(self, sentry_units, deployment, max_wait=60): """Turn ssl charm config option off, confirm that it is disabled on every unit. :param sentry_units: list of sentry units :param deployment: amulet deployment object pointer :param max_wait: maximum time to wait in seconds to confirm :returns: None if successful. Raise on error. """ 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) # Confirm tries = 0 ret = self.validate_rmq_ssl_disabled_units(sentry_units) while ret and tries < (max_wait / 4): time.sleep(4) self.log.debug('Attempt {}: {}'.format(tries, ret)) ret = self.validate_rmq_ssl_disabled_units(sentry_units) tries += 1 if ret: amulet.raise_status(amulet.FAIL, ret)
[ "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", ")", "# Confirm", "tries", "=", "0", "ret", "=", "self", ".", "validate_rmq_ssl_disabled_units", "(", "sentry_units", ")", "while", "ret", "and", "tries", "<", "(", "max_wait", "/", "4", ")", ":", "time", ".", "sleep", "(", "4", ")", "self", ".", "log", ".", "debug", "(", "'Attempt {}: {}'", ".", "format", "(", "tries", ",", "ret", ")", ")", "ret", "=", "self", ".", "validate_rmq_ssl_disabled_units", "(", "sentry_units", ")", "tries", "+=", "1", "if", "ret", ":", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "ret", ")" ]
Turn ssl charm config option off, confirm that it is disabled on every unit. :param sentry_units: list of sentry units :param deployment: amulet deployment object pointer :param max_wait: maximum time to wait in seconds to confirm :returns: None if successful. Raise on error.
[ "Turn", "ssl", "charm", "config", "option", "off", "confirm", "that", "it", "is", "disabled", "on", "every", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1376-L1404
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.connect_amqp_by_unit
def connect_amqp_by_unit(self, sentry_unit, ssl=False, port=None, fatal=True, username="testuser1", password="changeme"): """Establish and return a pika amqp connection to the rabbitmq service running on a rmq juju unit. :param sentry_unit: sentry unit pointer :param ssl: boolean, default to False :param port: amqp port, use defaults if None :param fatal: boolean, default to True (raises on connect error) :param username: amqp user name, default to testuser1 :param password: amqp user password :returns: pika amqp connection pointer or None if failed and non-fatal """ 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 not ssl and not port: port = 5672 self.log.debug('Connecting to amqp on {}:{} ({}) as ' '{}...'.format(host, port, unit_name, username)) try: credentials = pika.PlainCredentials(username, password) parameters = pika.ConnectionParameters(host=host, port=port, credentials=credentials, ssl=ssl, connection_attempts=3, retry_delay=5, socket_timeout=1) connection = pika.BlockingConnection(parameters) assert connection.is_open is True assert connection.is_closing is False self.log.debug('Connect OK') return connection except Exception as e: msg = ('amqp connection failed to {}:{} as ' '{} ({})'.format(host, port, username, str(e))) if fatal: amulet.raise_status(amulet.FAIL, msg) else: self.log.warn(msg) return None
python
def connect_amqp_by_unit(self, sentry_unit, ssl=False, port=None, fatal=True, username="testuser1", password="changeme"): """Establish and return a pika amqp connection to the rabbitmq service running on a rmq juju unit. :param sentry_unit: sentry unit pointer :param ssl: boolean, default to False :param port: amqp port, use defaults if None :param fatal: boolean, default to True (raises on connect error) :param username: amqp user name, default to testuser1 :param password: amqp user password :returns: pika amqp connection pointer or None if failed and non-fatal """ 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 not ssl and not port: port = 5672 self.log.debug('Connecting to amqp on {}:{} ({}) as ' '{}...'.format(host, port, unit_name, username)) try: credentials = pika.PlainCredentials(username, password) parameters = pika.ConnectionParameters(host=host, port=port, credentials=credentials, ssl=ssl, connection_attempts=3, retry_delay=5, socket_timeout=1) connection = pika.BlockingConnection(parameters) assert connection.is_open is True assert connection.is_closing is False self.log.debug('Connect OK') return connection except Exception as e: msg = ('amqp connection failed to {}:{} as ' '{} ({})'.format(host, port, username, str(e))) if fatal: amulet.raise_status(amulet.FAIL, msg) else: self.log.warn(msg) return None
[ "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", "not", "ssl", "and", "not", "port", ":", "port", "=", "5672", "self", ".", "log", ".", "debug", "(", "'Connecting to amqp on {}:{} ({}) as '", "'{}...'", ".", "format", "(", "host", ",", "port", ",", "unit_name", ",", "username", ")", ")", "try", ":", "credentials", "=", "pika", ".", "PlainCredentials", "(", "username", ",", "password", ")", "parameters", "=", "pika", ".", "ConnectionParameters", "(", "host", "=", "host", ",", "port", "=", "port", ",", "credentials", "=", "credentials", ",", "ssl", "=", "ssl", ",", "connection_attempts", "=", "3", ",", "retry_delay", "=", "5", ",", "socket_timeout", "=", "1", ")", "connection", "=", "pika", ".", "BlockingConnection", "(", "parameters", ")", "assert", "connection", ".", "is_open", "is", "True", "assert", "connection", ".", "is_closing", "is", "False", "self", ".", "log", ".", "debug", "(", "'Connect OK'", ")", "return", "connection", "except", "Exception", "as", "e", ":", "msg", "=", "(", "'amqp connection failed to {}:{} as '", "'{} ({})'", ".", "format", "(", "host", ",", "port", ",", "username", ",", "str", "(", "e", ")", ")", ")", "if", "fatal", ":", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", ")", "else", ":", "self", ".", "log", ".", "warn", "(", "msg", ")", "return", "None" ]
Establish and return a pika amqp connection to the rabbitmq service running on a rmq juju unit. :param sentry_unit: sentry unit pointer :param ssl: boolean, default to False :param port: amqp port, use defaults if None :param fatal: boolean, default to True (raises on connect error) :param username: amqp user name, default to testuser1 :param password: amqp user password :returns: pika amqp connection pointer or None if failed and non-fatal
[ "Establish", "and", "return", "a", "pika", "amqp", "connection", "to", "the", "rabbitmq", "service", "running", "on", "a", "rmq", "juju", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1406-L1452
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.publish_amqp_message_by_unit
def publish_amqp_message_by_unit(self, sentry_unit, message, queue="test", ssl=False, username="testuser1", password="changeme", port=None): """Publish an amqp message to a rmq juju unit. :param sentry_unit: sentry unit pointer :param message: amqp message string :param queue: message queue, default to test :param username: amqp user name, default to testuser1 :param password: amqp user password :param ssl: boolean, default to False :param port: amqp port, use defaults if None :returns: None. Raises exception if publish failed. """ self.log.debug('Publishing message to {} queue:\n{}'.format(queue, message)) connection = self.connect_amqp_by_unit(sentry_unit, ssl=ssl, port=port, username=username, password=password) # NOTE(beisner): extra debug here re: pika hang potential: # https://github.com/pika/pika/issues/297 # https://groups.google.com/forum/#!topic/rabbitmq-users/Ja0iyfF0Szw self.log.debug('Defining channel...') channel = connection.channel() self.log.debug('Declaring queue...') channel.queue_declare(queue=queue, auto_delete=False, durable=True) self.log.debug('Publishing message...') channel.basic_publish(exchange='', routing_key=queue, body=message) self.log.debug('Closing channel...') channel.close() self.log.debug('Closing connection...') connection.close()
python
def publish_amqp_message_by_unit(self, sentry_unit, message, queue="test", ssl=False, username="testuser1", password="changeme", port=None): """Publish an amqp message to a rmq juju unit. :param sentry_unit: sentry unit pointer :param message: amqp message string :param queue: message queue, default to test :param username: amqp user name, default to testuser1 :param password: amqp user password :param ssl: boolean, default to False :param port: amqp port, use defaults if None :returns: None. Raises exception if publish failed. """ self.log.debug('Publishing message to {} queue:\n{}'.format(queue, message)) connection = self.connect_amqp_by_unit(sentry_unit, ssl=ssl, port=port, username=username, password=password) # NOTE(beisner): extra debug here re: pika hang potential: # https://github.com/pika/pika/issues/297 # https://groups.google.com/forum/#!topic/rabbitmq-users/Ja0iyfF0Szw self.log.debug('Defining channel...') channel = connection.channel() self.log.debug('Declaring queue...') channel.queue_declare(queue=queue, auto_delete=False, durable=True) self.log.debug('Publishing message...') channel.basic_publish(exchange='', routing_key=queue, body=message) self.log.debug('Closing channel...') channel.close() self.log.debug('Closing connection...') connection.close()
[ "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", ",", "port", "=", "port", ",", "username", "=", "username", ",", "password", "=", "password", ")", "# NOTE(beisner): extra debug here re: pika hang potential:", "# https://github.com/pika/pika/issues/297", "# https://groups.google.com/forum/#!topic/rabbitmq-users/Ja0iyfF0Szw", "self", ".", "log", ".", "debug", "(", "'Defining channel...'", ")", "channel", "=", "connection", ".", "channel", "(", ")", "self", ".", "log", ".", "debug", "(", "'Declaring queue...'", ")", "channel", ".", "queue_declare", "(", "queue", "=", "queue", ",", "auto_delete", "=", "False", ",", "durable", "=", "True", ")", "self", ".", "log", ".", "debug", "(", "'Publishing message...'", ")", "channel", ".", "basic_publish", "(", "exchange", "=", "''", ",", "routing_key", "=", "queue", ",", "body", "=", "message", ")", "self", ".", "log", ".", "debug", "(", "'Closing channel...'", ")", "channel", ".", "close", "(", ")", "self", ".", "log", ".", "debug", "(", "'Closing connection...'", ")", "connection", ".", "close", "(", ")" ]
Publish an amqp message to a rmq juju unit. :param sentry_unit: sentry unit pointer :param message: amqp message string :param queue: message queue, default to test :param username: amqp user name, default to testuser1 :param password: amqp user password :param ssl: boolean, default to False :param port: amqp port, use defaults if None :returns: None. Raises exception if publish failed.
[ "Publish", "an", "amqp", "message", "to", "a", "rmq", "juju", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1454-L1489
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.get_amqp_message_by_unit
def get_amqp_message_by_unit(self, sentry_unit, queue="test", username="testuser1", password="changeme", ssl=False, port=None): """Get an amqp message from a rmq juju unit. :param sentry_unit: sentry unit pointer :param queue: message queue, default to test :param username: amqp user name, default to testuser1 :param password: amqp user password :param ssl: boolean, default to False :param port: amqp port, use defaults if None :returns: amqp message body as string. Raise if get fails. """ connection = self.connect_amqp_by_unit(sentry_unit, ssl=ssl, port=port, username=username, password=password) channel = connection.channel() method_frame, _, body = channel.basic_get(queue) if method_frame: self.log.debug('Retreived message from {} queue:\n{}'.format(queue, body)) channel.basic_ack(method_frame.delivery_tag) channel.close() connection.close() return body else: msg = 'No message retrieved.' amulet.raise_status(amulet.FAIL, msg)
python
def get_amqp_message_by_unit(self, sentry_unit, queue="test", username="testuser1", password="changeme", ssl=False, port=None): """Get an amqp message from a rmq juju unit. :param sentry_unit: sentry unit pointer :param queue: message queue, default to test :param username: amqp user name, default to testuser1 :param password: amqp user password :param ssl: boolean, default to False :param port: amqp port, use defaults if None :returns: amqp message body as string. Raise if get fails. """ connection = self.connect_amqp_by_unit(sentry_unit, ssl=ssl, port=port, username=username, password=password) channel = connection.channel() method_frame, _, body = channel.basic_get(queue) if method_frame: self.log.debug('Retreived message from {} queue:\n{}'.format(queue, body)) channel.basic_ack(method_frame.delivery_tag) channel.close() connection.close() return body else: msg = 'No message retrieved.' amulet.raise_status(amulet.FAIL, msg)
[ "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_frame", ",", "_", ",", "body", "=", "channel", ".", "basic_get", "(", "queue", ")", "if", "method_frame", ":", "self", ".", "log", ".", "debug", "(", "'Retreived message from {} queue:\\n{}'", ".", "format", "(", "queue", ",", "body", ")", ")", "channel", ".", "basic_ack", "(", "method_frame", ".", "delivery_tag", ")", "channel", ".", "close", "(", ")", "connection", ".", "close", "(", ")", "return", "body", "else", ":", "msg", "=", "'No message retrieved.'", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", ")" ]
Get an amqp message from a rmq juju unit. :param sentry_unit: sentry unit pointer :param queue: message queue, default to test :param username: amqp user name, default to testuser1 :param password: amqp user password :param ssl: boolean, default to False :param port: amqp port, use defaults if None :returns: amqp message body as string. Raise if get fails.
[ "Get", "an", "amqp", "message", "from", "a", "rmq", "juju", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1491-L1521
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_memcache
def validate_memcache(self, sentry_unit, conf, os_release, earliest_release=5, section='keystone_authtoken', check_kvs=None): """Check Memcache is running and is configured to be used Example call from Amulet test: def test_110_memcache(self): u.validate_memcache(self.neutron_api_sentry, '/etc/neutron/neutron.conf', self._get_openstack_release()) :param sentry_unit: sentry unit :param conf: OpenStack config file to check memcache settings :param os_release: Current OpenStack release int code :param earliest_release: Earliest Openstack release to check int code :param section: OpenStack config file section to check :param check_kvs: Dict of settings to check in config file :returns: None """ if os_release < earliest_release: self.log.debug('Skipping memcache checks for deployment. {} <' 'mitaka'.format(os_release)) return _kvs = check_kvs or {'memcached_servers': 'inet6:[::1]:11211'} self.log.debug('Checking memcached is running') ret = self.validate_services_by_name({sentry_unit: ['memcached']}) if ret: amulet.raise_status(amulet.FAIL, msg='Memcache running check' 'failed {}'.format(ret)) else: self.log.debug('OK') self.log.debug('Checking memcache url is configured in {}'.format( conf)) if self.validate_config_data(sentry_unit, conf, section, _kvs): message = "Memcache config error in: {}".format(conf) amulet.raise_status(amulet.FAIL, msg=message) else: self.log.debug('OK') self.log.debug('Checking memcache configuration in ' '/etc/memcached.conf') contents = self.file_contents_safe(sentry_unit, '/etc/memcached.conf', fatal=True) ubuntu_release, _ = self.run_cmd_unit(sentry_unit, 'lsb_release -cs') if CompareHostReleases(ubuntu_release) <= 'trusty': memcache_listen_addr = 'ip6-localhost' else: memcache_listen_addr = '::1' expected = { '-p': '11211', '-l': memcache_listen_addr} found = [] for key, value in expected.items(): for line in contents.split('\n'): if line.startswith(key): self.log.debug('Checking {} is set to {}'.format( key, value)) assert value == line.split()[-1] self.log.debug(line.split()[-1]) found.append(key) if sorted(found) == sorted(expected.keys()): self.log.debug('OK') else: message = "Memcache config error in: /etc/memcached.conf" amulet.raise_status(amulet.FAIL, msg=message)
python
def validate_memcache(self, sentry_unit, conf, os_release, earliest_release=5, section='keystone_authtoken', check_kvs=None): """Check Memcache is running and is configured to be used Example call from Amulet test: def test_110_memcache(self): u.validate_memcache(self.neutron_api_sentry, '/etc/neutron/neutron.conf', self._get_openstack_release()) :param sentry_unit: sentry unit :param conf: OpenStack config file to check memcache settings :param os_release: Current OpenStack release int code :param earliest_release: Earliest Openstack release to check int code :param section: OpenStack config file section to check :param check_kvs: Dict of settings to check in config file :returns: None """ if os_release < earliest_release: self.log.debug('Skipping memcache checks for deployment. {} <' 'mitaka'.format(os_release)) return _kvs = check_kvs or {'memcached_servers': 'inet6:[::1]:11211'} self.log.debug('Checking memcached is running') ret = self.validate_services_by_name({sentry_unit: ['memcached']}) if ret: amulet.raise_status(amulet.FAIL, msg='Memcache running check' 'failed {}'.format(ret)) else: self.log.debug('OK') self.log.debug('Checking memcache url is configured in {}'.format( conf)) if self.validate_config_data(sentry_unit, conf, section, _kvs): message = "Memcache config error in: {}".format(conf) amulet.raise_status(amulet.FAIL, msg=message) else: self.log.debug('OK') self.log.debug('Checking memcache configuration in ' '/etc/memcached.conf') contents = self.file_contents_safe(sentry_unit, '/etc/memcached.conf', fatal=True) ubuntu_release, _ = self.run_cmd_unit(sentry_unit, 'lsb_release -cs') if CompareHostReleases(ubuntu_release) <= 'trusty': memcache_listen_addr = 'ip6-localhost' else: memcache_listen_addr = '::1' expected = { '-p': '11211', '-l': memcache_listen_addr} found = [] for key, value in expected.items(): for line in contents.split('\n'): if line.startswith(key): self.log.debug('Checking {} is set to {}'.format( key, value)) assert value == line.split()[-1] self.log.debug(line.split()[-1]) found.append(key) if sorted(found) == sorted(expected.keys()): self.log.debug('OK') else: message = "Memcache config error in: /etc/memcached.conf" amulet.raise_status(amulet.FAIL, msg=message)
[ "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_servers'", ":", "'inet6:[::1]:11211'", "}", "self", ".", "log", ".", "debug", "(", "'Checking memcached is running'", ")", "ret", "=", "self", ".", "validate_services_by_name", "(", "{", "sentry_unit", ":", "[", "'memcached'", "]", "}", ")", "if", "ret", ":", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "'Memcache running check'", "'failed {}'", ".", "format", "(", "ret", ")", ")", "else", ":", "self", ".", "log", ".", "debug", "(", "'OK'", ")", "self", ".", "log", ".", "debug", "(", "'Checking memcache url is configured in {}'", ".", "format", "(", "conf", ")", ")", "if", "self", ".", "validate_config_data", "(", "sentry_unit", ",", "conf", ",", "section", ",", "_kvs", ")", ":", "message", "=", "\"Memcache config error in: {}\"", ".", "format", "(", "conf", ")", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "message", ")", "else", ":", "self", ".", "log", ".", "debug", "(", "'OK'", ")", "self", ".", "log", ".", "debug", "(", "'Checking memcache configuration in '", "'/etc/memcached.conf'", ")", "contents", "=", "self", ".", "file_contents_safe", "(", "sentry_unit", ",", "'/etc/memcached.conf'", ",", "fatal", "=", "True", ")", "ubuntu_release", ",", "_", "=", "self", ".", "run_cmd_unit", "(", "sentry_unit", ",", "'lsb_release -cs'", ")", "if", "CompareHostReleases", "(", "ubuntu_release", ")", "<=", "'trusty'", ":", "memcache_listen_addr", "=", "'ip6-localhost'", "else", ":", "memcache_listen_addr", "=", "'::1'", "expected", "=", "{", "'-p'", ":", "'11211'", ",", "'-l'", ":", "memcache_listen_addr", "}", "found", "=", "[", "]", "for", "key", ",", "value", "in", "expected", ".", "items", "(", ")", ":", "for", "line", "in", "contents", ".", "split", "(", "'\\n'", ")", ":", "if", "line", ".", "startswith", "(", "key", ")", ":", "self", ".", "log", ".", "debug", "(", "'Checking {} is set to {}'", ".", "format", "(", "key", ",", "value", ")", ")", "assert", "value", "==", "line", ".", "split", "(", ")", "[", "-", "1", "]", "self", ".", "log", ".", "debug", "(", "line", ".", "split", "(", ")", "[", "-", "1", "]", ")", "found", ".", "append", "(", "key", ")", "if", "sorted", "(", "found", ")", "==", "sorted", "(", "expected", ".", "keys", "(", ")", ")", ":", "self", ".", "log", ".", "debug", "(", "'OK'", ")", "else", ":", "message", "=", "\"Memcache config error in: /etc/memcached.conf\"", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "message", ")" ]
Check Memcache is running and is configured to be used Example call from Amulet test: def test_110_memcache(self): u.validate_memcache(self.neutron_api_sentry, '/etc/neutron/neutron.conf', self._get_openstack_release()) :param sentry_unit: sentry unit :param conf: OpenStack config file to check memcache settings :param os_release: Current OpenStack release int code :param earliest_release: Earliest Openstack release to check int code :param section: OpenStack config file section to check :param check_kvs: Dict of settings to check in config file :returns: None
[ "Check", "Memcache", "is", "running", "and", "is", "configured", "to", "be", "used" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1523-L1588
train
juju/charm-helpers
charmhelpers/coordinator.py
BaseCoordinator.acquire
def acquire(self, lock): '''Acquire the named lock, non-blocking. The lock may be granted immediately, or in a future hook. Returns True if the lock has been granted. The lock will be automatically released at the end of the hook in which it is granted. Do not mindlessly call this method, as it triggers a cascade of hooks. For example, if you call acquire() every time in your peers relation-changed hook you will end up with an infinite loop of hooks. It should almost always be guarded by some condition. ''' 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 {}'.format(lock)) # If the leader has granted the lock, yay. if self.granted(lock): self.msg('Acquired {}'.format(lock)) return True # If the unit making the request also happens to be the # leader, it must handle the request now. Even though the # request has been stored on the peers relation, the peers # relation-changed hook will not be triggered. if hookenv.is_leader(): return self.grant(lock, unit) return False
python
def acquire(self, lock): '''Acquire the named lock, non-blocking. The lock may be granted immediately, or in a future hook. Returns True if the lock has been granted. The lock will be automatically released at the end of the hook in which it is granted. Do not mindlessly call this method, as it triggers a cascade of hooks. For example, if you call acquire() every time in your peers relation-changed hook you will end up with an infinite loop of hooks. It should almost always be guarded by some condition. ''' 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 {}'.format(lock)) # If the leader has granted the lock, yay. if self.granted(lock): self.msg('Acquired {}'.format(lock)) return True # If the unit making the request also happens to be the # leader, it must handle the request now. Even though the # request has been stored on the peers relation, the peers # relation-changed hook will not be triggered. if hookenv.is_leader(): return self.grant(lock, unit) return False
[ "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 {}'", ".", "format", "(", "lock", ")", ")", "# If the leader has granted the lock, yay.", "if", "self", ".", "granted", "(", "lock", ")", ":", "self", ".", "msg", "(", "'Acquired {}'", ".", "format", "(", "lock", ")", ")", "return", "True", "# If the unit making the request also happens to be the", "# leader, it must handle the request now. Even though the", "# request has been stored on the peers relation, the peers", "# relation-changed hook will not be triggered.", "if", "hookenv", ".", "is_leader", "(", ")", ":", "return", "self", ".", "grant", "(", "lock", ",", "unit", ")", "return", "False" ]
Acquire the named lock, non-blocking. The lock may be granted immediately, or in a future hook. Returns True if the lock has been granted. The lock will be automatically released at the end of the hook in which it is granted. Do not mindlessly call this method, as it triggers a cascade of hooks. For example, if you call acquire() every time in your peers relation-changed hook you will end up with an infinite loop of hooks. It should almost always be guarded by some condition.
[ "Acquire", "the", "named", "lock", "non", "-", "blocking", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L301-L336
train
juju/charm-helpers
charmhelpers/coordinator.py
BaseCoordinator.granted
def granted(self, lock): '''Return True if a previously requested lock has been granted''' unit = hookenv.local_unit() ts = self.requests[unit].get(lock) if ts and self.grants.get(unit, {}).get(lock) == ts: return True return False
python
def granted(self, lock): '''Return True if a previously requested lock has been granted''' unit = hookenv.local_unit() ts = self.requests[unit].get(lock) if ts and self.grants.get(unit, {}).get(lock) == ts: return True return False
[ "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
[ "Return", "True", "if", "a", "previously", "requested", "lock", "has", "been", "granted" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L338-L344
train
juju/charm-helpers
charmhelpers/coordinator.py
BaseCoordinator.request_timestamp
def request_timestamp(self, lock): '''Return the timestamp of our outstanding request for lock, or None. Returns a datetime.datetime() UTC timestamp, with no tzinfo attribute. ''' ts = self.requests[hookenv.local_unit()].get(lock, None) if ts is not None: return datetime.strptime(ts, _timestamp_format)
python
def request_timestamp(self, lock): '''Return the timestamp of our outstanding request for lock, or None. Returns a datetime.datetime() UTC timestamp, with no tzinfo attribute. ''' ts = self.requests[hookenv.local_unit()].get(lock, None) if ts is not None: return datetime.strptime(ts, _timestamp_format)
[ "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. Returns a datetime.datetime() UTC timestamp, with no tzinfo attribute.
[ "Return", "the", "timestamp", "of", "our", "outstanding", "request", "for", "lock", "or", "None", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L350-L357
train
juju/charm-helpers
charmhelpers/coordinator.py
BaseCoordinator.grant
def grant(self, lock, unit): '''Maybe grant the lock to a unit. The decision to grant the lock or not is made for $lock by a corresponding method grant_$lock, which you may define in a subclass. If no such method is defined, the default_grant method is used. See Serial.default_grant() for details. ''' 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 list of units waiting for the lock. reqs = set() for u in self.requests: if u in granted: continue # In the granted set. Not wanted in the req list. for _lock, ts in self.requests[u].items(): if _lock == lock: reqs.add((ts, u)) queue = [t[1] for t in sorted(reqs)] if unit not in queue: return False # Unit has not requested the lock. # Locate custom logic, or fallback to the default. grant_func = getattr(self, 'grant_{}'.format(lock), self.default_grant) if grant_func(lock, unit, granted, queue): # Grant the lock. self.msg('Leader grants {} to {}'.format(lock, unit)) self.grants.setdefault(unit, {})[lock] = self.requests[unit][lock] return True return False
python
def grant(self, lock, unit): '''Maybe grant the lock to a unit. The decision to grant the lock or not is made for $lock by a corresponding method grant_$lock, which you may define in a subclass. If no such method is defined, the default_grant method is used. See Serial.default_grant() for details. ''' 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 list of units waiting for the lock. reqs = set() for u in self.requests: if u in granted: continue # In the granted set. Not wanted in the req list. for _lock, ts in self.requests[u].items(): if _lock == lock: reqs.add((ts, u)) queue = [t[1] for t in sorted(reqs)] if unit not in queue: return False # Unit has not requested the lock. # Locate custom logic, or fallback to the default. grant_func = getattr(self, 'grant_{}'.format(lock), self.default_grant) if grant_func(lock, unit, granted, queue): # Grant the lock. self.msg('Leader grants {} to {}'.format(lock, unit)) self.grants.setdefault(unit, {})[lock] = self.requests[unit][lock] return True return False
[ "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 list of units waiting for the lock.", "reqs", "=", "set", "(", ")", "for", "u", "in", "self", ".", "requests", ":", "if", "u", "in", "granted", ":", "continue", "# In the granted set. Not wanted in the req list.", "for", "_lock", ",", "ts", "in", "self", ".", "requests", "[", "u", "]", ".", "items", "(", ")", ":", "if", "_lock", "==", "lock", ":", "reqs", ".", "add", "(", "(", "ts", ",", "u", ")", ")", "queue", "=", "[", "t", "[", "1", "]", "for", "t", "in", "sorted", "(", "reqs", ")", "]", "if", "unit", "not", "in", "queue", ":", "return", "False", "# Unit has not requested the lock.", "# Locate custom logic, or fallback to the default.", "grant_func", "=", "getattr", "(", "self", ",", "'grant_{}'", ".", "format", "(", "lock", ")", ",", "self", ".", "default_grant", ")", "if", "grant_func", "(", "lock", ",", "unit", ",", "granted", ",", "queue", ")", ":", "# Grant the lock.", "self", ".", "msg", "(", "'Leader grants {} to {}'", ".", "format", "(", "lock", ",", "unit", ")", ")", "self", ".", "grants", ".", "setdefault", "(", "unit", ",", "{", "}", ")", "[", "lock", "]", "=", "self", ".", "requests", "[", "unit", "]", "[", "lock", "]", "return", "True", "return", "False" ]
Maybe grant the lock to a unit. The decision to grant the lock or not is made for $lock by a corresponding method grant_$lock, which you may define in a subclass. If no such method is defined, the default_grant method is used. See Serial.default_grant() for details.
[ "Maybe", "grant", "the", "lock", "to", "a", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L387-L427
train
juju/charm-helpers
charmhelpers/coordinator.py
BaseCoordinator.released
def released(self, unit, lock, timestamp): '''Called on the leader when it has released a lock. By default, does nothing but log messages. Override if you need to perform additional housekeeping when a lock is released, for example recording timestamps. ''' interval = _utcnow() - timestamp self.msg('Leader released {} from {}, held {}'.format(lock, unit, interval))
python
def released(self, unit, lock, timestamp): '''Called on the leader when it has released a lock. By default, does nothing but log messages. Override if you need to perform additional housekeeping when a lock is released, for example recording timestamps. ''' interval = _utcnow() - timestamp self.msg('Leader released {} from {}, held {}'.format(lock, unit, interval))
[ "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. By default, does nothing but log messages. Override if you need to perform additional housekeeping when a lock is released, for example recording timestamps.
[ "Called", "on", "the", "leader", "when", "it", "has", "released", "a", "lock", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L429-L438
train
juju/charm-helpers
charmhelpers/coordinator.py
BaseCoordinator.require
def require(self, lock, guard_func, *guard_args, **guard_kw): """Decorate a function to be run only when a lock is acquired. The lock is requested if the guard function returns True. The decorated function is called if the lock has been granted. """ 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): return f(*args, **kw) return None return wrapper return decorator
python
def require(self, lock, guard_func, *guard_args, **guard_kw): """Decorate a function to be run only when a lock is acquired. The lock is requested if the guard function returns True. The decorated function is called if the lock has been granted. """ 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): return f(*args, **kw) return None return wrapper return decorator
[ "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", ")", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kw", ")", "return", "None", "return", "wrapper", "return", "decorator" ]
Decorate a function to be run only when a lock is acquired. The lock is requested if the guard function returns True. The decorated function is called if the lock has been granted.
[ "Decorate", "a", "function", "to", "be", "run", "only", "when", "a", "lock", "is", "acquired", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L440-L457
train
juju/charm-helpers
charmhelpers/coordinator.py
BaseCoordinator.msg
def msg(self, msg): '''Emit a message. Override to customize log spam.''' hookenv.log('coordinator.{} {}'.format(self._name(), msg), level=hookenv.INFO)
python
def msg(self, msg): '''Emit a message. Override to customize log spam.''' hookenv.log('coordinator.{} {}'.format(self._name(), msg), level=hookenv.INFO)
[ "def", "msg", "(", "self", ",", "msg", ")", ":", "hookenv", ".", "log", "(", "'coordinator.{} {}'", ".", "format", "(", "self", ".", "_name", "(", ")", ",", "msg", ")", ",", "level", "=", "hookenv", ".", "INFO", ")" ]
Emit a message. Override to customize log spam.
[ "Emit", "a", "message", ".", "Override", "to", "customize", "log", "spam", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L459-L462
train
juju/charm-helpers
charmhelpers/__init__.py
deprecate
def deprecate(warning, date=None, log=None): """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. usage: @deprecate('use core/fetch/add_source() instead', '2017-04') def contributed_add_source_thing(...): ... And it then prints to the log ONCE that the function is deprecated. The reason for passing the logging function (log) is so that hookenv.log can be used for a charm if needed. :param warning: String to indicat where it has moved ot. :param date: optional sting, in YYYY-MM format to indicate when the function will definitely (probably) be removed. :param log: The log function to call to log. If not, logs to stdout """ 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, lines[0], lines[-1], f.__name__) except (IOError, TypeError): # assume it was local, so just use the name of the function f_name = f.__name__ if f_name not in __deprecated_functions: __deprecated_functions[f_name] = True s = "DEPRECATION WARNING: Function {} is being removed".format( f.__name__) if date: s = "{} on/around {}".format(s, date) if warning: s = "{} : {}".format(s, warning) if log: log(s) else: print(s) return f(*args, **kwargs) return wrapped_f return wrap
python
def deprecate(warning, date=None, log=None): """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. usage: @deprecate('use core/fetch/add_source() instead', '2017-04') def contributed_add_source_thing(...): ... And it then prints to the log ONCE that the function is deprecated. The reason for passing the logging function (log) is so that hookenv.log can be used for a charm if needed. :param warning: String to indicat where it has moved ot. :param date: optional sting, in YYYY-MM format to indicate when the function will definitely (probably) be removed. :param log: The log function to call to log. If not, logs to stdout """ 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, lines[0], lines[-1], f.__name__) except (IOError, TypeError): # assume it was local, so just use the name of the function f_name = f.__name__ if f_name not in __deprecated_functions: __deprecated_functions[f_name] = True s = "DEPRECATION WARNING: Function {} is being removed".format( f.__name__) if date: s = "{} on/around {}".format(s, date) if warning: s = "{} : {}".format(s, warning) if log: log(s) else: print(s) return f(*args, **kwargs) return wrapped_f return wrap
[ "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", ",", "lines", "[", "0", "]", ",", "lines", "[", "-", "1", "]", ",", "f", ".", "__name__", ")", "except", "(", "IOError", ",", "TypeError", ")", ":", "# assume it was local, so just use the name of the function", "f_name", "=", "f", ".", "__name__", "if", "f_name", "not", "in", "__deprecated_functions", ":", "__deprecated_functions", "[", "f_name", "]", "=", "True", "s", "=", "\"DEPRECATION WARNING: Function {} is being removed\"", ".", "format", "(", "f", ".", "__name__", ")", "if", "date", ":", "s", "=", "\"{} on/around {}\"", ".", "format", "(", "s", ",", "date", ")", "if", "warning", ":", "s", "=", "\"{} : {}\"", ".", "format", "(", "s", ",", "warning", ")", "if", "log", ":", "log", "(", "s", ")", "else", ":", "print", "(", "s", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapped_f", "return", "wrap" ]
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. usage: @deprecate('use core/fetch/add_source() instead', '2017-04') def contributed_add_source_thing(...): ... And it then prints to the log ONCE that the function is deprecated. The reason for passing the logging function (log) is so that hookenv.log can be used for a charm if needed. :param warning: String to indicat where it has moved ot. :param date: optional sting, in YYYY-MM format to indicate when the function will definitely (probably) be removed. :param log: The log function to call to log. If not, logs to stdout
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/__init__.py#L50-L97
train
juju/charm-helpers
charmhelpers/fetch/archiveurl.py
ArchiveUrlFetchHandler.download
def download(self, source, dest): """ Download an archive file. :param str source: URL pointing to an archive file. :param str dest: Local path location to download archive file to. """ # 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, query, fragment)) username, password = splitpasswd(auth) passman = HTTPPasswordMgrWithDefaultRealm() # Realm is set to None in add_password to force the username and password # to be used whatever the realm passman.add_password(None, source, username, password) authhandler = HTTPBasicAuthHandler(passman) opener = build_opener(authhandler) install_opener(opener) response = urlopen(source) try: with open(dest, 'wb') as dest_file: dest_file.write(response.read()) except Exception as e: if os.path.isfile(dest): os.unlink(dest) raise e
python
def download(self, source, dest): """ Download an archive file. :param str source: URL pointing to an archive file. :param str dest: Local path location to download archive file to. """ # 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, query, fragment)) username, password = splitpasswd(auth) passman = HTTPPasswordMgrWithDefaultRealm() # Realm is set to None in add_password to force the username and password # to be used whatever the realm passman.add_password(None, source, username, password) authhandler = HTTPBasicAuthHandler(passman) opener = build_opener(authhandler) install_opener(opener) response = urlopen(source) try: with open(dest, 'wb') as dest_file: dest_file.write(response.read()) except Exception as e: if os.path.isfile(dest): os.unlink(dest) raise e
[ "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", ",", "query", ",", "fragment", ")", ")", "username", ",", "password", "=", "splitpasswd", "(", "auth", ")", "passman", "=", "HTTPPasswordMgrWithDefaultRealm", "(", ")", "# Realm is set to None in add_password to force the username and password", "# to be used whatever the realm", "passman", ".", "add_password", "(", "None", ",", "source", ",", "username", ",", "password", ")", "authhandler", "=", "HTTPBasicAuthHandler", "(", "passman", ")", "opener", "=", "build_opener", "(", "authhandler", ")", "install_opener", "(", "opener", ")", "response", "=", "urlopen", "(", "source", ")", "try", ":", "with", "open", "(", "dest", ",", "'wb'", ")", "as", "dest_file", ":", "dest_file", ".", "write", "(", "response", ".", "read", "(", ")", ")", "except", "Exception", "as", "e", ":", "if", "os", ".", "path", ".", "isfile", "(", "dest", ")", ":", "os", ".", "unlink", "(", "dest", ")", "raise", "e" ]
Download an archive file. :param str source: URL pointing to an archive file. :param str dest: Local path location to download archive file to.
[ "Download", "an", "archive", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/archiveurl.py#L85-L114
train
juju/charm-helpers
charmhelpers/fetch/archiveurl.py
ArchiveUrlFetchHandler.install
def install(self, source, dest=None, checksum=None, hash_type='sha1'): """ Download and install an archive file, with optional checksum validation. The checksum can also be given on the `source` URL's fragment. For example:: handler.install('http://example.com/file.tgz#sha1=deadbeef') :param str source: URL pointing to an archive file. :param str dest: Local destination path to install to. If not given, installs to `$CHARM_DIR/archives/archive_file_name`. :param str checksum: If given, validate the archive file after download. :param str hash_type: Algorithm used to generate `checksum`. Can be any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. """ 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, os.path.basename(url_parts.path)) try: self.download(source, dld_file) except URLError as e: raise UnhandledSource(e.reason) except OSError as e: raise UnhandledSource(e.strerror) options = parse_qs(url_parts.fragment) for key, value in options.items(): if not six.PY3: algorithms = hashlib.algorithms else: algorithms = hashlib.algorithms_available if key in algorithms: if len(value) != 1: raise TypeError( "Expected 1 hash value, not %d" % len(value)) expected = value[0] check_hash(dld_file, expected, key) if checksum: check_hash(dld_file, checksum, hash_type) return extract(dld_file, dest)
python
def install(self, source, dest=None, checksum=None, hash_type='sha1'): """ Download and install an archive file, with optional checksum validation. The checksum can also be given on the `source` URL's fragment. For example:: handler.install('http://example.com/file.tgz#sha1=deadbeef') :param str source: URL pointing to an archive file. :param str dest: Local destination path to install to. If not given, installs to `$CHARM_DIR/archives/archive_file_name`. :param str checksum: If given, validate the archive file after download. :param str hash_type: Algorithm used to generate `checksum`. Can be any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. """ 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, os.path.basename(url_parts.path)) try: self.download(source, dld_file) except URLError as e: raise UnhandledSource(e.reason) except OSError as e: raise UnhandledSource(e.strerror) options = parse_qs(url_parts.fragment) for key, value in options.items(): if not six.PY3: algorithms = hashlib.algorithms else: algorithms = hashlib.algorithms_available if key in algorithms: if len(value) != 1: raise TypeError( "Expected 1 hash value, not %d" % len(value)) expected = value[0] check_hash(dld_file, expected, key) if checksum: check_hash(dld_file, checksum, hash_type) return extract(dld_file, dest)
[ "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", ",", "os", ".", "path", ".", "basename", "(", "url_parts", ".", "path", ")", ")", "try", ":", "self", ".", "download", "(", "source", ",", "dld_file", ")", "except", "URLError", "as", "e", ":", "raise", "UnhandledSource", "(", "e", ".", "reason", ")", "except", "OSError", "as", "e", ":", "raise", "UnhandledSource", "(", "e", ".", "strerror", ")", "options", "=", "parse_qs", "(", "url_parts", ".", "fragment", ")", "for", "key", ",", "value", "in", "options", ".", "items", "(", ")", ":", "if", "not", "six", ".", "PY3", ":", "algorithms", "=", "hashlib", ".", "algorithms", "else", ":", "algorithms", "=", "hashlib", ".", "algorithms_available", "if", "key", "in", "algorithms", ":", "if", "len", "(", "value", ")", "!=", "1", ":", "raise", "TypeError", "(", "\"Expected 1 hash value, not %d\"", "%", "len", "(", "value", ")", ")", "expected", "=", "value", "[", "0", "]", "check_hash", "(", "dld_file", ",", "expected", ",", "key", ")", "if", "checksum", ":", "check_hash", "(", "dld_file", ",", "checksum", ",", "hash_type", ")", "return", "extract", "(", "dld_file", ",", "dest", ")" ]
Download and install an archive file, with optional checksum validation. The checksum can also be given on the `source` URL's fragment. For example:: handler.install('http://example.com/file.tgz#sha1=deadbeef') :param str source: URL pointing to an archive file. :param str dest: Local destination path to install to. If not given, installs to `$CHARM_DIR/archives/archive_file_name`. :param str checksum: If given, validate the archive file after download. :param str hash_type: Algorithm used to generate `checksum`. Can be any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc.
[ "Download", "and", "install", "an", "archive", "file", "with", "optional", "checksum", "validation", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/archiveurl.py#L122-L165
train
juju/charm-helpers
charmhelpers/fetch/python/debug.py
set_trace
def set_trace(addr=DEFAULT_ADDR, port=DEFAULT_PORT): """ Set a trace point using the remote debugger """ 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 Exception: _error("Cannot start a remote debug session on %s:%s" % (addr, port))
python
def set_trace(addr=DEFAULT_ADDR, port=DEFAULT_PORT): """ Set a trace point using the remote debugger """ 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 Exception: _error("Cannot start a remote debug session on %s:%s" % (addr, port))
[ "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", "Exception", ":", "_error", "(", "\"Cannot start a remote debug session on %s:%s\"", "%", "(", "addr", ",", "port", ")", ")" ]
Set a trace point using the remote debugger
[ "Set", "a", "trace", "point", "using", "the", "remote", "debugger" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/debug.py#L41-L54
train
juju/charm-helpers
charmhelpers/contrib/mellanox/infiniband.py
device_info
def device_info(device): """Returns a DeviceInfo object with the current device settings""" 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 image GUID: (.*)": "sys_guid", } device = DeviceInfo() for line in status: for expression, key in regexes.items(): matches = re.search(expression, line) if matches: setattr(device, key, matches.group(1)) return device
python
def device_info(device): """Returns a DeviceInfo object with the current device settings""" 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 image GUID: (.*)": "sys_guid", } device = DeviceInfo() for line in status: for expression, key in regexes.items(): matches = re.search(expression, line) if matches: setattr(device, key, matches.group(1)) return device
[ "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 image GUID: (.*)\"", ":", "\"sys_guid\"", ",", "}", "device", "=", "DeviceInfo", "(", ")", "for", "line", "in", "status", ":", "for", "expression", ",", "key", "in", "regexes", ".", "items", "(", ")", ":", "matches", "=", "re", ".", "search", "(", "expression", ",", "line", ")", "if", "matches", ":", "setattr", "(", "device", ",", "key", ",", "matches", ".", "group", "(", "1", ")", ")", "return", "device" ]
Returns a DeviceInfo object with the current device settings
[ "Returns", "a", "DeviceInfo", "object", "with", "the", "current", "device", "settings" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/mellanox/infiniband.py#L111-L134
train
juju/charm-helpers
charmhelpers/contrib/mellanox/infiniband.py
ipoib_interfaces
def ipoib_interfaces(): """Return a list of IPOIB capable ethernet 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 interface %s" % interface, level=INFO) continue return interfaces
python
def ipoib_interfaces(): """Return a list of IPOIB capable ethernet 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 interface %s" % interface, level=INFO) continue return interfaces
[ "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 interface %s\"", "%", "interface", ",", "level", "=", "INFO", ")", "continue", "return", "interfaces" ]
Return a list of IPOIB capable ethernet interfaces
[ "Return", "a", "list", "of", "IPOIB", "capable", "ethernet", "interfaces" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/mellanox/infiniband.py#L137-L153
train
juju/charm-helpers
charmhelpers/contrib/hardening/host/checks/login.py
get_audits
def get_audits(): """Get OS hardening login.defs audits. :returns: dictionary of audits """ audits = [TemplatedFile('/etc/login.defs', LoginContext(), template_dir=TEMPLATES_DIR, user='root', group='root', mode=0o0444)] return audits
python
def get_audits(): """Get OS hardening login.defs audits. :returns: dictionary of audits """ audits = [TemplatedFile('/etc/login.defs', LoginContext(), template_dir=TEMPLATES_DIR, user='root', group='root', mode=0o0444)] return audits
[ "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. :returns: dictionary of audits
[ "Get", "OS", "hardening", "login", ".", "defs", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/login.py#L22-L30
train
juju/charm-helpers
charmhelpers/contrib/hardening/utils.py
_get_defaults
def _get_defaults(modules): """Load the default config for the provided modules. :param modules: stack modules config defaults to lookup. :returns: modules default config dictionary. """ default = os.path.join(os.path.dirname(__file__), 'defaults/%s.yaml' % (modules)) return yaml.safe_load(open(default))
python
def _get_defaults(modules): """Load the default config for the provided modules. :param modules: stack modules config defaults to lookup. :returns: modules default config dictionary. """ default = os.path.join(os.path.dirname(__file__), 'defaults/%s.yaml' % (modules)) return yaml.safe_load(open(default))
[ "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. :param modules: stack modules config defaults to lookup. :returns: modules default config dictionary.
[ "Load", "the", "default", "config", "for", "the", "provided", "modules", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L37-L45
train
juju/charm-helpers
charmhelpers/contrib/hardening/utils.py
_get_schema
def _get_schema(modules): """Load the config schema for the provided modules. NOTE: this schema is intended to have 1-1 relationship with they keys in the default config and is used a means to verify valid overrides provided by the user. :param modules: stack modules config schema to lookup. :returns: modules default schema dictionary. """ schema = os.path.join(os.path.dirname(__file__), 'defaults/%s.yaml.schema' % (modules)) return yaml.safe_load(open(schema))
python
def _get_schema(modules): """Load the config schema for the provided modules. NOTE: this schema is intended to have 1-1 relationship with they keys in the default config and is used a means to verify valid overrides provided by the user. :param modules: stack modules config schema to lookup. :returns: modules default schema dictionary. """ schema = os.path.join(os.path.dirname(__file__), 'defaults/%s.yaml.schema' % (modules)) return yaml.safe_load(open(schema))
[ "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. NOTE: this schema is intended to have 1-1 relationship with they keys in the default config and is used a means to verify valid overrides provided by the user. :param modules: stack modules config schema to lookup. :returns: modules default schema dictionary.
[ "Load", "the", "config", "schema", "for", "the", "provided", "modules", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L48-L60
train
juju/charm-helpers
charmhelpers/contrib/hardening/utils.py
_get_user_provided_overrides
def _get_user_provided_overrides(modules): """Load user-provided config overrides. :param modules: stack modules to lookup in user overrides yaml file. :returns: overrides dictionary. """ 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 settings and settings.get(modules): log("Applying '%s' overrides" % (modules), level=DEBUG) return settings.get(modules) log("No overrides found for '%s'" % (modules), level=DEBUG) else: log("No hardening config overrides file '%s' found in charm " "root dir" % (overrides), level=DEBUG) return {}
python
def _get_user_provided_overrides(modules): """Load user-provided config overrides. :param modules: stack modules to lookup in user overrides yaml file. :returns: overrides dictionary. """ 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 settings and settings.get(modules): log("Applying '%s' overrides" % (modules), level=DEBUG) return settings.get(modules) log("No overrides found for '%s'" % (modules), level=DEBUG) else: log("No hardening config overrides file '%s' found in charm " "root dir" % (overrides), level=DEBUG) return {}
[ "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", "settings", "and", "settings", ".", "get", "(", "modules", ")", ":", "log", "(", "\"Applying '%s' overrides\"", "%", "(", "modules", ")", ",", "level", "=", "DEBUG", ")", "return", "settings", ".", "get", "(", "modules", ")", "log", "(", "\"No overrides found for '%s'\"", "%", "(", "modules", ")", ",", "level", "=", "DEBUG", ")", "else", ":", "log", "(", "\"No hardening config overrides file '%s' found in charm \"", "\"root dir\"", "%", "(", "overrides", ")", ",", "level", "=", "DEBUG", ")", "return", "{", "}" ]
Load user-provided config overrides. :param modules: stack modules to lookup in user overrides yaml file. :returns: overrides dictionary.
[ "Load", "user", "-", "provided", "config", "overrides", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L63-L84
train
juju/charm-helpers
charmhelpers/contrib/hardening/utils.py
_apply_overrides
def _apply_overrides(settings, overrides, schema): """Get overrides config overlayed onto modules defaults. :param modules: require stack modules config. :returns: dictionary of modules config with user overrides applied. """ 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 Exception("Unexpected type found in schema '%s'" % type(schema[k]), level=ERROR) else: log("Unknown override key '%s' - ignoring" % (k), level=INFO) return settings
python
def _apply_overrides(settings, overrides, schema): """Get overrides config overlayed onto modules defaults. :param modules: require stack modules config. :returns: dictionary of modules config with user overrides applied. """ 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 Exception("Unexpected type found in schema '%s'" % type(schema[k]), level=ERROR) else: log("Unknown override key '%s' - ignoring" % (k), level=INFO) return settings
[ "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", "Exception", "(", "\"Unexpected type found in schema '%s'\"", "%", "type", "(", "schema", "[", "k", "]", ")", ",", "level", "=", "ERROR", ")", "else", ":", "log", "(", "\"Unknown override key '%s' - ignoring\"", "%", "(", "k", ")", ",", "level", "=", "INFO", ")", "return", "settings" ]
Get overrides config overlayed onto modules defaults. :param modules: require stack modules config. :returns: dictionary of modules config with user overrides applied.
[ "Get", "overrides", "config", "overlayed", "onto", "modules", "defaults", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L87-L107
train
juju/charm-helpers
charmhelpers/contrib/hardening/utils.py
ensure_permissions
def ensure_permissions(path, user, group, permissions, maxdepth=-1): """Ensure permissions for path. If path is a file, apply to file and return. If path is a directory, apply recursively (if required) to directory contents and return. :param user: user name :param group: group name :param permissions: octal permissions :param maxdepth: maximum recursion depth. A negative maxdepth allows infinite recursion and maxdepth=0 means no recursion. :returns: None """ 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.chmod(path, permissions) if maxdepth == 0: log("Max recursion depth reached - skipping further recursion", level=DEBUG) return elif maxdepth > 0: maxdepth -= 1 if os.path.isdir(path): contents = glob.glob("%s/*" % (path)) for c in contents: ensure_permissions(c, user=user, group=group, permissions=permissions, maxdepth=maxdepth)
python
def ensure_permissions(path, user, group, permissions, maxdepth=-1): """Ensure permissions for path. If path is a file, apply to file and return. If path is a directory, apply recursively (if required) to directory contents and return. :param user: user name :param group: group name :param permissions: octal permissions :param maxdepth: maximum recursion depth. A negative maxdepth allows infinite recursion and maxdepth=0 means no recursion. :returns: None """ 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.chmod(path, permissions) if maxdepth == 0: log("Max recursion depth reached - skipping further recursion", level=DEBUG) return elif maxdepth > 0: maxdepth -= 1 if os.path.isdir(path): contents = glob.glob("%s/*" % (path)) for c in contents: ensure_permissions(c, user=user, group=group, permissions=permissions, maxdepth=maxdepth)
[ "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", ".", "chmod", "(", "path", ",", "permissions", ")", "if", "maxdepth", "==", "0", ":", "log", "(", "\"Max recursion depth reached - skipping further recursion\"", ",", "level", "=", "DEBUG", ")", "return", "elif", "maxdepth", ">", "0", ":", "maxdepth", "-=", "1", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "contents", "=", "glob", ".", "glob", "(", "\"%s/*\"", "%", "(", "path", ")", ")", "for", "c", "in", "contents", ":", "ensure_permissions", "(", "c", ",", "user", "=", "user", ",", "group", "=", "group", ",", "permissions", "=", "permissions", ",", "maxdepth", "=", "maxdepth", ")" ]
Ensure permissions for path. If path is a file, apply to file and return. If path is a directory, apply recursively (if required) to directory contents and return. :param user: user name :param group: group name :param permissions: octal permissions :param maxdepth: maximum recursion depth. A negative maxdepth allows infinite recursion and maxdepth=0 means no recursion. :returns: None
[ "Ensure", "permissions", "for", "path", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L122-L155
train
juju/charm-helpers
charmhelpers/core/sysctl.py
create
def create(sysctl_dict, sysctl_file, ignore=False): """Creates a sysctl.conf file from a YAML associative array :param sysctl_dict: a dict or YAML-formatted string of sysctl options eg "{ 'kernel.max_pid': 1337 }" :type sysctl_dict: str :param sysctl_file: path to the sysctl file to be saved :type sysctl_file: str or unicode :param ignore: If True, ignore "unknown variable" errors. :type ignore: bool :returns: None """ 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 with open(sysctl_file, "w") as fd: for key, value in sysctl_dict_parsed.items(): fd.write("{}={}\n".format(key, value)) log("Updating sysctl_file: {} values: {}".format(sysctl_file, sysctl_dict_parsed), level=DEBUG) call = ["sysctl", "-p", sysctl_file] if ignore: call.append("-e") check_call(call)
python
def create(sysctl_dict, sysctl_file, ignore=False): """Creates a sysctl.conf file from a YAML associative array :param sysctl_dict: a dict or YAML-formatted string of sysctl options eg "{ 'kernel.max_pid': 1337 }" :type sysctl_dict: str :param sysctl_file: path to the sysctl file to be saved :type sysctl_file: str or unicode :param ignore: If True, ignore "unknown variable" errors. :type ignore: bool :returns: None """ 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 with open(sysctl_file, "w") as fd: for key, value in sysctl_dict_parsed.items(): fd.write("{}={}\n".format(key, value)) log("Updating sysctl_file: {} values: {}".format(sysctl_file, sysctl_dict_parsed), level=DEBUG) call = ["sysctl", "-p", sysctl_file] if ignore: call.append("-e") check_call(call)
[ "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", "with", "open", "(", "sysctl_file", ",", "\"w\"", ")", "as", "fd", ":", "for", "key", ",", "value", "in", "sysctl_dict_parsed", ".", "items", "(", ")", ":", "fd", ".", "write", "(", "\"{}={}\\n\"", ".", "format", "(", "key", ",", "value", ")", ")", "log", "(", "\"Updating sysctl_file: {} values: {}\"", ".", "format", "(", "sysctl_file", ",", "sysctl_dict_parsed", ")", ",", "level", "=", "DEBUG", ")", "call", "=", "[", "\"sysctl\"", ",", "\"-p\"", ",", "sysctl_file", "]", "if", "ignore", ":", "call", ".", "append", "(", "\"-e\"", ")", "check_call", "(", "call", ")" ]
Creates a sysctl.conf file from a YAML associative array :param sysctl_dict: a dict or YAML-formatted string of sysctl options eg "{ 'kernel.max_pid': 1337 }" :type sysctl_dict: str :param sysctl_file: path to the sysctl file to be saved :type sysctl_file: str or unicode :param ignore: If True, ignore "unknown variable" errors. :type ignore: bool :returns: None
[ "Creates", "a", "sysctl", ".", "conf", "file", "from", "a", "YAML", "associative", "array" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/sysctl.py#L31-L65
train
juju/charm-helpers
charmhelpers/contrib/openstack/ip.py
canonical_url
def canonical_url(configs, endpoint_type=PUBLIC): """Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :param configs: OSTemplateRenderer config templating object to inspect for a complete https context. :param endpoint_type: str endpoint type to resolve. :param returns: str base URL for services on the current service unit. """ scheme = _get_scheme(configs) address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address)
python
def canonical_url(configs, endpoint_type=PUBLIC): """Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :param configs: OSTemplateRenderer config templating object to inspect for a complete https context. :param endpoint_type: str endpoint type to resolve. :param returns: str base URL for services on the current service unit. """ scheme = _get_scheme(configs) address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address)
[ "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. :param configs: OSTemplateRenderer config templating object to inspect for a complete https context. :param endpoint_type: str endpoint type to resolve. :param returns: str base URL for services on the current service unit.
[ "Returns", "the", "correct", "HTTP", "URL", "to", "this", "host", "given", "the", "state", "of", "HTTPS", "configuration", "hacluster", "and", "charm", "configuration", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ip.py#L64-L79
train
juju/charm-helpers
charmhelpers/contrib/openstack/ip.py
_get_address_override
def _get_address_override(endpoint_type=PUBLIC): """Returns any address overrides that the user has defined based on the endpoint type. Note: this function allows for the service name to be inserted into the address if the user specifies {service_name}.somehost.org. :param endpoint_type: the type of endpoint to retrieve the override value for. :returns: any endpoint address or hostname that the user has overridden or None if an override is not present. """ 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())
python
def _get_address_override(endpoint_type=PUBLIC): """Returns any address overrides that the user has defined based on the endpoint type. Note: this function allows for the service name to be inserted into the address if the user specifies {service_name}.somehost.org. :param endpoint_type: the type of endpoint to retrieve the override value for. :returns: any endpoint address or hostname that the user has overridden or None if an override is not present. """ 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())
[ "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. Note: this function allows for the service name to be inserted into the address if the user specifies {service_name}.somehost.org. :param endpoint_type: the type of endpoint to retrieve the override value for. :returns: any endpoint address or hostname that the user has overridden or None if an override is not present.
[ "Returns", "any", "address", "overrides", "that", "the", "user", "has", "defined", "based", "on", "the", "endpoint", "type", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ip.py#L97-L114
train
juju/charm-helpers
charmhelpers/contrib/openstack/ip.py
resolve_address
def resolve_address(endpoint_type=PUBLIC, override=True): """Return unit address depending on net config. If unit is clustered with vip(s) and has net splits defined, return vip on correct network. If clustered with no nets defined, return primary vip. If not clustered, return unit address ensuring address is on configured net split if one is configured, or a Juju 2.0 extra-binding has been used. :param endpoint_type: Network endpoing type :param override: Accept hostname overrides or not """ 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'] net_addr = config(net_type) net_fallback = ADDRESS_MAP[endpoint_type]['fallback'] binding = ADDRESS_MAP[endpoint_type]['binding'] clustered = is_clustered() if clustered and vips: if net_addr: for vip in vips: if is_address_in_network(net_addr, vip): resolved_address = vip break else: # NOTE: endeavour to check vips against network space # bindings try: bound_cidr = resolve_network_cidr( network_get_primary_address(binding) ) for vip in vips: if is_address_in_network(bound_cidr, vip): resolved_address = vip break except (NotImplementedError, NoNetworkBinding): # If no net-splits configured and no support for extra # bindings/network spaces so we expect a single vip resolved_address = vips[0] else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr(exc_list=vips)[0] else: fallback_addr = unit_get(net_fallback) if net_addr: resolved_address = get_address_in_network(net_addr, fallback_addr) else: # NOTE: only try to use extra bindings if legacy network # configuration is not in use try: resolved_address = network_get_primary_address(binding) except (NotImplementedError, NoNetworkBinding): resolved_address = fallback_addr if resolved_address is None: raise ValueError("Unable to resolve a suitable IP address based on " "charm state and configuration. (net_type=%s, " "clustered=%s)" % (net_type, clustered)) return resolved_address
python
def resolve_address(endpoint_type=PUBLIC, override=True): """Return unit address depending on net config. If unit is clustered with vip(s) and has net splits defined, return vip on correct network. If clustered with no nets defined, return primary vip. If not clustered, return unit address ensuring address is on configured net split if one is configured, or a Juju 2.0 extra-binding has been used. :param endpoint_type: Network endpoing type :param override: Accept hostname overrides or not """ 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'] net_addr = config(net_type) net_fallback = ADDRESS_MAP[endpoint_type]['fallback'] binding = ADDRESS_MAP[endpoint_type]['binding'] clustered = is_clustered() if clustered and vips: if net_addr: for vip in vips: if is_address_in_network(net_addr, vip): resolved_address = vip break else: # NOTE: endeavour to check vips against network space # bindings try: bound_cidr = resolve_network_cidr( network_get_primary_address(binding) ) for vip in vips: if is_address_in_network(bound_cidr, vip): resolved_address = vip break except (NotImplementedError, NoNetworkBinding): # If no net-splits configured and no support for extra # bindings/network spaces so we expect a single vip resolved_address = vips[0] else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr(exc_list=vips)[0] else: fallback_addr = unit_get(net_fallback) if net_addr: resolved_address = get_address_in_network(net_addr, fallback_addr) else: # NOTE: only try to use extra bindings if legacy network # configuration is not in use try: resolved_address = network_get_primary_address(binding) except (NotImplementedError, NoNetworkBinding): resolved_address = fallback_addr if resolved_address is None: raise ValueError("Unable to resolve a suitable IP address based on " "charm state and configuration. (net_type=%s, " "clustered=%s)" % (net_type, clustered)) return resolved_address
[ "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'", "]", "net_addr", "=", "config", "(", "net_type", ")", "net_fallback", "=", "ADDRESS_MAP", "[", "endpoint_type", "]", "[", "'fallback'", "]", "binding", "=", "ADDRESS_MAP", "[", "endpoint_type", "]", "[", "'binding'", "]", "clustered", "=", "is_clustered", "(", ")", "if", "clustered", "and", "vips", ":", "if", "net_addr", ":", "for", "vip", "in", "vips", ":", "if", "is_address_in_network", "(", "net_addr", ",", "vip", ")", ":", "resolved_address", "=", "vip", "break", "else", ":", "# NOTE: endeavour to check vips against network space", "# bindings", "try", ":", "bound_cidr", "=", "resolve_network_cidr", "(", "network_get_primary_address", "(", "binding", ")", ")", "for", "vip", "in", "vips", ":", "if", "is_address_in_network", "(", "bound_cidr", ",", "vip", ")", ":", "resolved_address", "=", "vip", "break", "except", "(", "NotImplementedError", ",", "NoNetworkBinding", ")", ":", "# If no net-splits configured and no support for extra", "# bindings/network spaces so we expect a single vip", "resolved_address", "=", "vips", "[", "0", "]", "else", ":", "if", "config", "(", "'prefer-ipv6'", ")", ":", "fallback_addr", "=", "get_ipv6_addr", "(", "exc_list", "=", "vips", ")", "[", "0", "]", "else", ":", "fallback_addr", "=", "unit_get", "(", "net_fallback", ")", "if", "net_addr", ":", "resolved_address", "=", "get_address_in_network", "(", "net_addr", ",", "fallback_addr", ")", "else", ":", "# NOTE: only try to use extra bindings if legacy network", "# configuration is not in use", "try", ":", "resolved_address", "=", "network_get_primary_address", "(", "binding", ")", "except", "(", "NotImplementedError", ",", "NoNetworkBinding", ")", ":", "resolved_address", "=", "fallback_addr", "if", "resolved_address", "is", "None", ":", "raise", "ValueError", "(", "\"Unable to resolve a suitable IP address based on \"", "\"charm state and configuration. (net_type=%s, \"", "\"clustered=%s)\"", "%", "(", "net_type", ",", "clustered", ")", ")", "return", "resolved_address" ]
Return unit address depending on net config. If unit is clustered with vip(s) and has net splits defined, return vip on correct network. If clustered with no nets defined, return primary vip. If not clustered, return unit address ensuring address is on configured net split if one is configured, or a Juju 2.0 extra-binding has been used. :param endpoint_type: Network endpoing type :param override: Accept hostname overrides or not
[ "Return", "unit", "address", "depending", "on", "net", "config", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ip.py#L117-L187
train
juju/charm-helpers
charmhelpers/core/hugepage.py
hugepage_support
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): """Enable hugepages on system. Args: user (str) -- Username to allow access to hugepages to group (str) -- Group name to own hugepages nr_hugepages (int) -- Number of pages to reserve max_map_count (int) -- Number of Virtual Memory Areas a process can own mnt_point (str) -- Directory to mount hugepages on pagesize (str) -- Size of hugepages mount (bool) -- Whether to Mount hugepages """ group_info = add_group(group) gid = group_info.gr_gid add_user_to_group(user, group) if max_map_count < 2 * nr_hugepages: max_map_count = 2 * nr_hugepages sysctl_settings = { 'vm.nr_hugepages': nr_hugepages, 'vm.max_map_count': max_map_count, 'vm.hugetlb_shm_group': gid, } if set_shmmax: shmmax_current = int(check_output(['sysctl', '-n', 'kernel.shmmax'])) shmmax_minsize = bytes_from_string(pagesize) * nr_hugepages if shmmax_minsize > shmmax_current: sysctl_settings['kernel.shmmax'] = shmmax_minsize sysctl.create(yaml.dump(sysctl_settings), '/etc/sysctl.d/10-hugepage.conf') mkdir(mnt_point, owner='root', group='root', perms=0o755, force=False) lfstab = fstab.Fstab() fstab_entry = lfstab.get_entry_by_attr('mountpoint', mnt_point) if fstab_entry: lfstab.remove_entry(fstab_entry) entry = lfstab.Entry('nodev', mnt_point, 'hugetlbfs', 'mode=1770,gid={},pagesize={}'.format(gid, pagesize), 0, 0) lfstab.add_entry(entry) if mount: fstab_mount(mnt_point)
python
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): """Enable hugepages on system. Args: user (str) -- Username to allow access to hugepages to group (str) -- Group name to own hugepages nr_hugepages (int) -- Number of pages to reserve max_map_count (int) -- Number of Virtual Memory Areas a process can own mnt_point (str) -- Directory to mount hugepages on pagesize (str) -- Size of hugepages mount (bool) -- Whether to Mount hugepages """ group_info = add_group(group) gid = group_info.gr_gid add_user_to_group(user, group) if max_map_count < 2 * nr_hugepages: max_map_count = 2 * nr_hugepages sysctl_settings = { 'vm.nr_hugepages': nr_hugepages, 'vm.max_map_count': max_map_count, 'vm.hugetlb_shm_group': gid, } if set_shmmax: shmmax_current = int(check_output(['sysctl', '-n', 'kernel.shmmax'])) shmmax_minsize = bytes_from_string(pagesize) * nr_hugepages if shmmax_minsize > shmmax_current: sysctl_settings['kernel.shmmax'] = shmmax_minsize sysctl.create(yaml.dump(sysctl_settings), '/etc/sysctl.d/10-hugepage.conf') mkdir(mnt_point, owner='root', group='root', perms=0o755, force=False) lfstab = fstab.Fstab() fstab_entry = lfstab.get_entry_by_attr('mountpoint', mnt_point) if fstab_entry: lfstab.remove_entry(fstab_entry) entry = lfstab.Entry('nodev', mnt_point, 'hugetlbfs', 'mode=1770,gid={},pagesize={}'.format(gid, pagesize), 0, 0) lfstab.add_entry(entry) if mount: fstab_mount(mnt_point)
[ "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", ":", "max_map_count", "=", "2", "*", "nr_hugepages", "sysctl_settings", "=", "{", "'vm.nr_hugepages'", ":", "nr_hugepages", ",", "'vm.max_map_count'", ":", "max_map_count", ",", "'vm.hugetlb_shm_group'", ":", "gid", ",", "}", "if", "set_shmmax", ":", "shmmax_current", "=", "int", "(", "check_output", "(", "[", "'sysctl'", ",", "'-n'", ",", "'kernel.shmmax'", "]", ")", ")", "shmmax_minsize", "=", "bytes_from_string", "(", "pagesize", ")", "*", "nr_hugepages", "if", "shmmax_minsize", ">", "shmmax_current", ":", "sysctl_settings", "[", "'kernel.shmmax'", "]", "=", "shmmax_minsize", "sysctl", ".", "create", "(", "yaml", ".", "dump", "(", "sysctl_settings", ")", ",", "'/etc/sysctl.d/10-hugepage.conf'", ")", "mkdir", "(", "mnt_point", ",", "owner", "=", "'root'", ",", "group", "=", "'root'", ",", "perms", "=", "0o755", ",", "force", "=", "False", ")", "lfstab", "=", "fstab", ".", "Fstab", "(", ")", "fstab_entry", "=", "lfstab", ".", "get_entry_by_attr", "(", "'mountpoint'", ",", "mnt_point", ")", "if", "fstab_entry", ":", "lfstab", ".", "remove_entry", "(", "fstab_entry", ")", "entry", "=", "lfstab", ".", "Entry", "(", "'nodev'", ",", "mnt_point", ",", "'hugetlbfs'", ",", "'mode=1770,gid={},pagesize={}'", ".", "format", "(", "gid", ",", "pagesize", ")", ",", "0", ",", "0", ")", "lfstab", ".", "add_entry", "(", "entry", ")", "if", "mount", ":", "fstab_mount", "(", "mnt_point", ")" ]
Enable hugepages on system. Args: user (str) -- Username to allow access to hugepages to group (str) -- Group name to own hugepages nr_hugepages (int) -- Number of pages to reserve max_map_count (int) -- Number of Virtual Memory Areas a process can own mnt_point (str) -- Directory to mount hugepages on pagesize (str) -- Size of hugepages mount (bool) -- Whether to Mount hugepages
[ "Enable", "hugepages", "on", "system", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hugepage.py#L30-L69
train
juju/charm-helpers
charmhelpers/contrib/hardening/audits/apache.py
DisabledModuleAudit.ensure_compliance
def ensure_compliance(self): """Ensures that the modules are not loaded.""" 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(module) if len(non_compliant_modules) == 0: return for module in non_compliant_modules: self._disable_module(module) self._restart_apache() except subprocess.CalledProcessError as e: log('Error occurred auditing apache module compliance. ' 'This may have been already reported. ' 'Output is: %s' % e.output, level=ERROR)
python
def ensure_compliance(self): """Ensures that the modules are not loaded.""" 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(module) if len(non_compliant_modules) == 0: return for module in non_compliant_modules: self._disable_module(module) self._restart_apache() except subprocess.CalledProcessError as e: log('Error occurred auditing apache module compliance. ' 'This may have been already reported. ' 'Output is: %s' % e.output, level=ERROR)
[ "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", "(", "module", ")", "if", "len", "(", "non_compliant_modules", ")", "==", "0", ":", "return", "for", "module", "in", "non_compliant_modules", ":", "self", ".", "_disable_module", "(", "module", ")", "self", ".", "_restart_apache", "(", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "log", "(", "'Error occurred auditing apache module compliance. '", "'This may have been already reported. '", "'Output is: %s'", "%", "e", ".", "output", ",", "level", "=", "ERROR", ")" ]
Ensures that the modules are not loaded.
[ "Ensures", "that", "the", "modules", "are", "not", "loaded", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/apache.py#L43-L66
train
juju/charm-helpers
charmhelpers/contrib/hardening/audits/apache.py
DisabledModuleAudit._get_loaded_modules
def _get_loaded_modules(): """Returns the modules which are enabled in Apache.""" 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 output which is stripped # out by the regex. matcher = re.search(r'^ (\S*)_module (\S*)', line) if matcher: modules.append(matcher.group(1)) return modules
python
def _get_loaded_modules(): """Returns the modules which are enabled in Apache.""" 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 output which is stripped # out by the regex. matcher = re.search(r'^ (\S*)_module (\S*)', line) if matcher: modules.append(matcher.group(1)) return modules
[ "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 output which is stripped", "# out by the regex.", "matcher", "=", "re", ".", "search", "(", "r'^ (\\S*)_module (\\S*)'", ",", "line", ")", "if", "matcher", ":", "modules", ".", "append", "(", "matcher", ".", "group", "(", "1", ")", ")", "return", "modules" ]
Returns the modules which are enabled in Apache.
[ "Returns", "the", "modules", "which", "are", "enabled", "in", "Apache", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/apache.py#L69-L83
train
juju/charm-helpers
charmhelpers/contrib/hardening/audits/apache.py
DisabledModuleAudit._disable_module
def _disable_module(module): """Disables the specified module in Apache.""" 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. ' 'Output is: %s' % (module, e.output), level=ERROR)
python
def _disable_module(module): """Disables the specified module in Apache.""" 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. ' 'Output is: %s' % (module, e.output), level=ERROR)
[ "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. '", "'Output is: %s'", "%", "(", "module", ",", "e", ".", "output", ")", ",", "level", "=", "ERROR", ")" ]
Disables the specified module in Apache.
[ "Disables", "the", "specified", "module", "in", "Apache", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/apache.py#L86-L95
train
juju/charm-helpers
charmhelpers/contrib/hardening/templating.py
get_template_path
def get_template_path(template_dir, path): """Returns the template file which would be used to render the path. The path to the template file is returned. :param template_dir: the directory the templates are located in :param path: the file path to be written to. :returns: path to the template file """ return os.path.join(template_dir, os.path.basename(path))
python
def get_template_path(template_dir, path): """Returns the template file which would be used to render the path. The path to the template file is returned. :param template_dir: the directory the templates are located in :param path: the file path to be written to. :returns: path to the template file """ return os.path.join(template_dir, os.path.basename(path))
[ "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. The path to the template file is returned. :param template_dir: the directory the templates are located in :param path: the file path to be written to. :returns: path to the template file
[ "Returns", "the", "template", "file", "which", "would", "be", "used", "to", "render", "the", "path", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/templating.py#L44-L52
train
juju/charm-helpers
charmhelpers/contrib/hardening/templating.py
render_and_write
def render_and_write(template_dir, path, context): """Renders the specified template into the file. :param template_dir: the directory to load the template from :param path: the path to write the templated contents to :param context: the parameters to pass to the rendering engine """ 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.render(context) if not rendered_content: log("Render returned None - skipping '%s'" % path, level=WARNING) return write(path, rendered_content.encode('utf-8').strip()) log('Wrote template %s' % path, level=DEBUG)
python
def render_and_write(template_dir, path, context): """Renders the specified template into the file. :param template_dir: the directory to load the template from :param path: the path to write the templated contents to :param context: the parameters to pass to the rendering engine """ 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.render(context) if not rendered_content: log("Render returned None - skipping '%s'" % path, level=WARNING) return write(path, rendered_content.encode('utf-8').strip()) log('Wrote template %s' % path, level=DEBUG)
[ "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", ".", "render", "(", "context", ")", "if", "not", "rendered_content", ":", "log", "(", "\"Render returned None - skipping '%s'\"", "%", "path", ",", "level", "=", "WARNING", ")", "return", "write", "(", "path", ",", "rendered_content", ".", "encode", "(", "'utf-8'", ")", ".", "strip", "(", ")", ")", "log", "(", "'Wrote template %s'", "%", "path", ",", "level", "=", "DEBUG", ")" ]
Renders the specified template into the file. :param template_dir: the directory to load the template from :param path: the path to write the templated contents to :param context: the parameters to pass to the rendering engine
[ "Renders", "the", "specified", "template", "into", "the", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/templating.py#L55-L73
train
juju/charm-helpers
charmhelpers/contrib/hardening/host/checks/apt.py
get_audits
def get_audits(): """Get OS hardening apt audits. :returns: dictionary of 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: audits.append(RestrictedPackages(security_packages)) return audits
python
def get_audits(): """Get OS hardening apt audits. :returns: dictionary of 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: audits.append(RestrictedPackages(security_packages)) return audits
[ "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", ":", "audits", ".", "append", "(", "RestrictedPackages", "(", "security_packages", ")", ")", "return", "audits" ]
Get OS hardening apt audits. :returns: dictionary of audits
[ "Get", "OS", "hardening", "apt", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/apt.py#L22-L37
train
juju/charm-helpers
charmhelpers/contrib/hardening/host/checks/pam.py
get_audits
def get_audits(): """Get OS hardening PAM authentication audits. :returns: dictionary of 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(DeletedFile('/usr/share/pam-configs/tally2')) return audits
python
def get_audits(): """Get OS hardening PAM authentication audits. :returns: dictionary of 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(DeletedFile('/usr/share/pam-configs/tally2')) return audits
[ "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", "(", "DeletedFile", "(", "'/usr/share/pam-configs/tally2'", ")", ")", "return", "audits" ]
Get OS hardening PAM authentication audits. :returns: dictionary of audits
[ "Get", "OS", "hardening", "PAM", "authentication", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/pam.py#L38-L55
train
juju/charm-helpers
charmhelpers/contrib/ansible/__init__.py
install_ansible_support
def install_ansible_support(from_ppa=True, ppa_location='ppa:rquillo/ansible'): """Installs the ansible package. By default it is installed from the `PPA`_ linked from the ansible `website`_ or from a ppa specified by a charm config.. .. _PPA: https://launchpad.net/~rquillo/+archive/ansible .. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu If from_ppa is empty, you must ensure that the package is available from a configured repository. """ 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.write('localhost ansible_connection=local ansible_remote_tmp=/root/.ansible/tmp')
python
def install_ansible_support(from_ppa=True, ppa_location='ppa:rquillo/ansible'): """Installs the ansible package. By default it is installed from the `PPA`_ linked from the ansible `website`_ or from a ppa specified by a charm config.. .. _PPA: https://launchpad.net/~rquillo/+archive/ansible .. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu If from_ppa is empty, you must ensure that the package is available from a configured repository. """ 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.write('localhost ansible_connection=local ansible_remote_tmp=/root/.ansible/tmp')
[ "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", ".", "write", "(", "'localhost ansible_connection=local ansible_remote_tmp=/root/.ansible/tmp'", ")" ]
Installs the ansible package. By default it is installed from the `PPA`_ linked from the ansible `website`_ or from a ppa specified by a charm config.. .. _PPA: https://launchpad.net/~rquillo/+archive/ansible .. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu If from_ppa is empty, you must ensure that the package is available from a configured repository.
[ "Installs", "the", "ansible", "package", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ansible/__init__.py#L120-L137
train
juju/charm-helpers
charmhelpers/contrib/ansible/__init__.py
AnsibleHooks.execute
def execute(self, args): """Execute the hook followed by the playbook using the hook as tag.""" 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, tags=[hook_name], extra_vars=extra_vars)
python
def execute(self, args): """Execute the hook followed by the playbook using the hook as tag.""" 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, tags=[hook_name], extra_vars=extra_vars)
[ "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", ",", "tags", "=", "[", "hook_name", "]", ",", "extra_vars", "=", "extra_vars", ")" ]
Execute the hook followed by the playbook using the hook as tag.
[ "Execute", "the", "hook", "followed", "by", "the", "playbook", "using", "the", "hook", "as", "tag", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ansible/__init__.py#L219-L229
train
juju/charm-helpers
charmhelpers/contrib/ansible/__init__.py
AnsibleHooks.action
def action(self, *action_names): """Decorator, registering them as actions""" 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.register_action(decorated.__name__, wrapper) if '_' in decorated.__name__: self.register_action( decorated.__name__.replace('_', '-'), wrapper) return wrapper return action_wrapper
python
def action(self, *action_names): """Decorator, registering them as actions""" 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.register_action(decorated.__name__, wrapper) if '_' in decorated.__name__: self.register_action( decorated.__name__.replace('_', '-'), wrapper) return wrapper return action_wrapper
[ "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", ".", "register_action", "(", "decorated", ".", "__name__", ",", "wrapper", ")", "if", "'_'", "in", "decorated", ".", "__name__", ":", "self", ".", "register_action", "(", "decorated", ".", "__name__", ".", "replace", "(", "'_'", ",", "'-'", ")", ",", "wrapper", ")", "return", "wrapper", "return", "action_wrapper" ]
Decorator, registering them as actions
[ "Decorator", "registering", "them", "as", "actions" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ansible/__init__.py#L231-L252
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment.get_logger
def get_logger(self, name="deployment-logger", level=logging.DEBUG): """Get a logger object that will log to stdout.""" 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(fmt) logger.addHandler(handler) logger.setLevel(level) return logger
python
def get_logger(self, name="deployment-logger", level=logging.DEBUG): """Get a logger object that will log to stdout.""" 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(fmt) logger.addHandler(handler) logger.setLevel(level) return logger
[ "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", "(", "fmt", ")", "logger", ".", "addHandler", "(", "handler", ")", "logger", ".", "setLevel", "(", "level", ")", "return", "logger" ]
Get a logger object that will log to stdout.
[ "Get", "a", "logger", "object", "that", "will", "log", "to", "stdout", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L49-L63
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment._determine_branch_locations
def _determine_branch_locations(self, other_services): """Determine the branch locations for the other services. Determine if the local branch being tested is derived from its stable or next (dev) branch, and based on this, use the corresonding stable or next branches for the 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 location has been explicitly set, use it if svc.get('location'): continue if svc['name'] in base_charms: # NOTE: not all charms have support for all series we # want/need to test against, so fix to most recent # that each base charm supports target_series = self.series if self.series not in base_charms[svc['name']]: target_series = base_charms[svc['name']][-1] svc['location'] = 'cs:{}/{}'.format(target_series, svc['name']) elif self.stable: svc['location'] = 'cs:{}/{}'.format(self.series, svc['name']) else: svc['location'] = 'cs:~openstack-charmers-next/{}/{}'.format( self.series, svc['name'] ) return other_services
python
def _determine_branch_locations(self, other_services): """Determine the branch locations for the other services. Determine if the local branch being tested is derived from its stable or next (dev) branch, and based on this, use the corresonding stable or next branches for the 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 location has been explicitly set, use it if svc.get('location'): continue if svc['name'] in base_charms: # NOTE: not all charms have support for all series we # want/need to test against, so fix to most recent # that each base charm supports target_series = self.series if self.series not in base_charms[svc['name']]: target_series = base_charms[svc['name']][-1] svc['location'] = 'cs:{}/{}'.format(target_series, svc['name']) elif self.stable: svc['location'] = 'cs:{}/{}'.format(self.series, svc['name']) else: svc['location'] = 'cs:~openstack-charmers-next/{}/{}'.format( self.series, svc['name'] ) return other_services
[ "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 location has been explicitly set, use it", "if", "svc", ".", "get", "(", "'location'", ")", ":", "continue", "if", "svc", "[", "'name'", "]", "in", "base_charms", ":", "# NOTE: not all charms have support for all series we", "# want/need to test against, so fix to most recent", "# that each base charm supports", "target_series", "=", "self", ".", "series", "if", "self", ".", "series", "not", "in", "base_charms", "[", "svc", "[", "'name'", "]", "]", ":", "target_series", "=", "base_charms", "[", "svc", "[", "'name'", "]", "]", "[", "-", "1", "]", "svc", "[", "'location'", "]", "=", "'cs:{}/{}'", ".", "format", "(", "target_series", ",", "svc", "[", "'name'", "]", ")", "elif", "self", ".", "stable", ":", "svc", "[", "'location'", "]", "=", "'cs:{}/{}'", ".", "format", "(", "self", ".", "series", ",", "svc", "[", "'name'", "]", ")", "else", ":", "svc", "[", "'location'", "]", "=", "'cs:~openstack-charmers-next/{}/{}'", ".", "format", "(", "self", ".", "series", ",", "svc", "[", "'name'", "]", ")", "return", "other_services" ]
Determine the branch locations for the other services. Determine if the local branch being tested is derived from its stable or next (dev) branch, and based on this, use the corresonding stable or next branches for the other_services.
[ "Determine", "the", "branch", "locations", "for", "the", "other", "services", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L65-L103
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment._auto_wait_for_status
def _auto_wait_for_status(self, message=None, exclude_services=None, include_only=None, timeout=None): """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. Examples of message usage: Wait for all unit status to CONTAIN any case of 'ready' or 'ok': message = re.compile('.*ready.*|.*ok.*', re.IGNORECASE) Wait for all units to reach this status (exact match): message = re.compile('^Unit is ready and clustered$') Wait for all units to reach any one of these (exact match): message = re.compile('Unit is ready|OK|Ready') Wait for at least one unit to reach this status (exact match): message = {'ready'} See Amulet's sentry.wait_for_messages() for message usage detail. https://github.com/juju/amulet/blob/master/amulet/sentry.py :param message: Expected status match :param exclude_services: List of juju service names to ignore, not to be used in conjuction with include_only. :param include_only: List of juju service names to exclusively check, not to be used in conjuction with exclude_services. :param timeout: Maximum time in seconds to wait for status match :returns: None. Raises if timeout is hit. """ 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 = self.d.services.keys() if exclude_services and include_only: raise ValueError('exclude_services can not be used ' 'with include_only') if message: if isinstance(message, re._pattern_type): match = message.pattern else: match = message self.log.debug('Custom extended status wait match: ' '{}'.format(match)) else: self.log.debug('Default extended status wait match: contains ' 'READY (case-insensitive)') message = re.compile('.*ready.*', re.IGNORECASE) if exclude_services: self.log.debug('Excluding services from extended status match: ' '{}'.format(exclude_services)) else: exclude_services = [] if include_only: services = include_only else: services = list(set(all_services) - set(exclude_services)) self.log.debug('Waiting up to {}s for extended status on services: ' '{}'.format(timeout, services)) service_messages = {service: message for service in services} # Check for idleness self.d.sentry.wait(timeout=timeout) # Check for error states and bail early self.d.sentry.wait_for_status(self.d.juju_env, services, timeout=timeout) # Check for ready messages self.d.sentry.wait_for_messages(service_messages, timeout=timeout) self.log.info('OK')
python
def _auto_wait_for_status(self, message=None, exclude_services=None, include_only=None, timeout=None): """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. Examples of message usage: Wait for all unit status to CONTAIN any case of 'ready' or 'ok': message = re.compile('.*ready.*|.*ok.*', re.IGNORECASE) Wait for all units to reach this status (exact match): message = re.compile('^Unit is ready and clustered$') Wait for all units to reach any one of these (exact match): message = re.compile('Unit is ready|OK|Ready') Wait for at least one unit to reach this status (exact match): message = {'ready'} See Amulet's sentry.wait_for_messages() for message usage detail. https://github.com/juju/amulet/blob/master/amulet/sentry.py :param message: Expected status match :param exclude_services: List of juju service names to ignore, not to be used in conjuction with include_only. :param include_only: List of juju service names to exclusively check, not to be used in conjuction with exclude_services. :param timeout: Maximum time in seconds to wait for status match :returns: None. Raises if timeout is hit. """ 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 = self.d.services.keys() if exclude_services and include_only: raise ValueError('exclude_services can not be used ' 'with include_only') if message: if isinstance(message, re._pattern_type): match = message.pattern else: match = message self.log.debug('Custom extended status wait match: ' '{}'.format(match)) else: self.log.debug('Default extended status wait match: contains ' 'READY (case-insensitive)') message = re.compile('.*ready.*', re.IGNORECASE) if exclude_services: self.log.debug('Excluding services from extended status match: ' '{}'.format(exclude_services)) else: exclude_services = [] if include_only: services = include_only else: services = list(set(all_services) - set(exclude_services)) self.log.debug('Waiting up to {}s for extended status on services: ' '{}'.format(timeout, services)) service_messages = {service: message for service in services} # Check for idleness self.d.sentry.wait(timeout=timeout) # Check for error states and bail early self.d.sentry.wait_for_status(self.d.juju_env, services, timeout=timeout) # Check for ready messages self.d.sentry.wait_for_messages(service_messages, timeout=timeout) self.log.info('OK')
[ "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", "=", "self", ".", "d", ".", "services", ".", "keys", "(", ")", "if", "exclude_services", "and", "include_only", ":", "raise", "ValueError", "(", "'exclude_services can not be used '", "'with include_only'", ")", "if", "message", ":", "if", "isinstance", "(", "message", ",", "re", ".", "_pattern_type", ")", ":", "match", "=", "message", ".", "pattern", "else", ":", "match", "=", "message", "self", ".", "log", ".", "debug", "(", "'Custom extended status wait match: '", "'{}'", ".", "format", "(", "match", ")", ")", "else", ":", "self", ".", "log", ".", "debug", "(", "'Default extended status wait match: contains '", "'READY (case-insensitive)'", ")", "message", "=", "re", ".", "compile", "(", "'.*ready.*'", ",", "re", ".", "IGNORECASE", ")", "if", "exclude_services", ":", "self", ".", "log", ".", "debug", "(", "'Excluding services from extended status match: '", "'{}'", ".", "format", "(", "exclude_services", ")", ")", "else", ":", "exclude_services", "=", "[", "]", "if", "include_only", ":", "services", "=", "include_only", "else", ":", "services", "=", "list", "(", "set", "(", "all_services", ")", "-", "set", "(", "exclude_services", ")", ")", "self", ".", "log", ".", "debug", "(", "'Waiting up to {}s for extended status on services: '", "'{}'", ".", "format", "(", "timeout", ",", "services", ")", ")", "service_messages", "=", "{", "service", ":", "message", "for", "service", "in", "services", "}", "# Check for idleness", "self", ".", "d", ".", "sentry", ".", "wait", "(", "timeout", "=", "timeout", ")", "# Check for error states and bail early", "self", ".", "d", ".", "sentry", ".", "wait_for_status", "(", "self", ".", "d", ".", "juju_env", ",", "services", ",", "timeout", "=", "timeout", ")", "# Check for ready messages", "self", ".", "d", ".", "sentry", ".", "wait_for_messages", "(", "service_messages", ",", "timeout", "=", "timeout", ")", "self", ".", "log", ".", "info", "(", "'OK'", ")" ]
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. Examples of message usage: Wait for all unit status to CONTAIN any case of 'ready' or 'ok': message = re.compile('.*ready.*|.*ok.*', re.IGNORECASE) Wait for all units to reach this status (exact match): message = re.compile('^Unit is ready and clustered$') Wait for all units to reach any one of these (exact match): message = re.compile('Unit is ready|OK|Ready') Wait for at least one unit to reach this status (exact match): message = {'ready'} See Amulet's sentry.wait_for_messages() for message usage detail. https://github.com/juju/amulet/blob/master/amulet/sentry.py :param message: Expected status match :param exclude_services: List of juju service names to ignore, not to be used in conjuction with include_only. :param include_only: List of juju service names to exclusively check, not to be used in conjuction with exclude_services. :param timeout: Maximum time in seconds to wait for status match :returns: None. Raises if timeout is hit.
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L192-L269
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment._get_openstack_release
def _get_openstack_release(self): """Get openstack release. Return an integer representing the enum value of the openstack release. """ # 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', 'cloud:trusty-liberty'): self.trusty_liberty, ('trusty', 'cloud:trusty-mitaka'): self.trusty_mitaka, ('xenial', None): self.xenial_mitaka, ('xenial', 'cloud:xenial-newton'): self.xenial_newton, ('xenial', 'cloud:xenial-ocata'): self.xenial_ocata, ('xenial', 'cloud:xenial-pike'): self.xenial_pike, ('xenial', 'cloud:xenial-queens'): self.xenial_queens, ('yakkety', None): self.yakkety_newton, ('zesty', None): self.zesty_ocata, ('artful', None): self.artful_pike, ('bionic', None): self.bionic_queens, ('bionic', 'cloud:bionic-rocky'): self.bionic_rocky, ('bionic', 'cloud:bionic-stein'): self.bionic_stein, ('cosmic', None): self.cosmic_rocky, ('disco', None): self.disco_stein, } return releases[(self.series, self.openstack)]
python
def _get_openstack_release(self): """Get openstack release. Return an integer representing the enum value of the openstack release. """ # 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', 'cloud:trusty-liberty'): self.trusty_liberty, ('trusty', 'cloud:trusty-mitaka'): self.trusty_mitaka, ('xenial', None): self.xenial_mitaka, ('xenial', 'cloud:xenial-newton'): self.xenial_newton, ('xenial', 'cloud:xenial-ocata'): self.xenial_ocata, ('xenial', 'cloud:xenial-pike'): self.xenial_pike, ('xenial', 'cloud:xenial-queens'): self.xenial_queens, ('yakkety', None): self.yakkety_newton, ('zesty', None): self.zesty_ocata, ('artful', None): self.artful_pike, ('bionic', None): self.bionic_queens, ('bionic', 'cloud:bionic-rocky'): self.bionic_rocky, ('bionic', 'cloud:bionic-stein'): self.bionic_stein, ('cosmic', None): self.cosmic_rocky, ('disco', None): self.disco_stein, } return releases[(self.series, self.openstack)]
[ "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'", ",", "'cloud:trusty-liberty'", ")", ":", "self", ".", "trusty_liberty", ",", "(", "'trusty'", ",", "'cloud:trusty-mitaka'", ")", ":", "self", ".", "trusty_mitaka", ",", "(", "'xenial'", ",", "None", ")", ":", "self", ".", "xenial_mitaka", ",", "(", "'xenial'", ",", "'cloud:xenial-newton'", ")", ":", "self", ".", "xenial_newton", ",", "(", "'xenial'", ",", "'cloud:xenial-ocata'", ")", ":", "self", ".", "xenial_ocata", ",", "(", "'xenial'", ",", "'cloud:xenial-pike'", ")", ":", "self", ".", "xenial_pike", ",", "(", "'xenial'", ",", "'cloud:xenial-queens'", ")", ":", "self", ".", "xenial_queens", ",", "(", "'yakkety'", ",", "None", ")", ":", "self", ".", "yakkety_newton", ",", "(", "'zesty'", ",", "None", ")", ":", "self", ".", "zesty_ocata", ",", "(", "'artful'", ",", "None", ")", ":", "self", ".", "artful_pike", ",", "(", "'bionic'", ",", "None", ")", ":", "self", ".", "bionic_queens", ",", "(", "'bionic'", ",", "'cloud:bionic-rocky'", ")", ":", "self", ".", "bionic_rocky", ",", "(", "'bionic'", ",", "'cloud:bionic-stein'", ")", ":", "self", ".", "bionic_stein", ",", "(", "'cosmic'", ",", "None", ")", ":", "self", ".", "cosmic_rocky", ",", "(", "'disco'", ",", "None", ")", ":", "self", ".", "disco_stein", ",", "}", "return", "releases", "[", "(", "self", ".", "series", ",", "self", ".", "openstack", ")", "]" ]
Get openstack release. Return an integer representing the enum value of the openstack release.
[ "Get", "openstack", "release", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L271-L300
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment._get_openstack_release_string
def _get_openstack_release_string(self): """Get openstack release string. Return a string representing the openstack release. """ releases = OrderedDict([ ('trusty', 'icehouse'), ('xenial', 'mitaka'), ('yakkety', 'newton'), ('zesty', 'ocata'), ('artful', 'pike'), ('bionic', 'queens'), ('cosmic', 'rocky'), ('disco', 'stein'), ]) if self.openstack: os_origin = self.openstack.split(':')[1] return os_origin.split('%s-' % self.series)[1].split('/')[0] else: return releases[self.series]
python
def _get_openstack_release_string(self): """Get openstack release string. Return a string representing the openstack release. """ releases = OrderedDict([ ('trusty', 'icehouse'), ('xenial', 'mitaka'), ('yakkety', 'newton'), ('zesty', 'ocata'), ('artful', 'pike'), ('bionic', 'queens'), ('cosmic', 'rocky'), ('disco', 'stein'), ]) if self.openstack: os_origin = self.openstack.split(':')[1] return os_origin.split('%s-' % self.series)[1].split('/')[0] else: return releases[self.series]
[ "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", ".", "openstack", ".", "split", "(", "':'", ")", "[", "1", "]", "return", "os_origin", ".", "split", "(", "'%s-'", "%", "self", ".", "series", ")", "[", "1", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", "else", ":", "return", "releases", "[", "self", ".", "series", "]" ]
Get openstack release string. Return a string representing the openstack release.
[ "Get", "openstack", "release", "string", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L302-L321
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment.get_ceph_expected_pools
def get_ceph_expected_pools(self, radosgw=False): """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.""" 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 = [ 'rbd', 'cinder-ceph', 'glance' ] else: # Pike and later pools = [ 'cinder-ceph', 'glance' ] if radosgw: pools.extend([ '.rgw.root', '.rgw.control', '.rgw', '.rgw.gc', '.users.uid' ]) return pools
python
def get_ceph_expected_pools(self, radosgw=False): """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.""" 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 = [ 'rbd', 'cinder-ceph', 'glance' ] else: # Pike and later pools = [ 'cinder-ceph', 'glance' ] if radosgw: pools.extend([ '.rgw.root', '.rgw.control', '.rgw', '.rgw.gc', '.users.uid' ]) return pools
[ "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", "=", "[", "'rbd'", ",", "'cinder-ceph'", ",", "'glance'", "]", "else", ":", "# Pike and later", "pools", "=", "[", "'cinder-ceph'", ",", "'glance'", "]", "if", "radosgw", ":", "pools", ".", "extend", "(", "[", "'.rgw.root'", ",", "'.rgw.control'", ",", "'.rgw'", ",", "'.rgw.gc'", ",", "'.users.uid'", "]", ")", "return", "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.
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L323-L361
train
juju/charm-helpers
charmhelpers/osplatform.py
get_platform
def get_platform(): """Return the current OS platform. For example: if current os platform is Ubuntu then a string "ubuntu" will be returned (which is the name of the module). This string is used to decide which platform module should be imported. """ # 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_platform: return "centos" elif "debian" in current_platform: # Stock Python does not detect Ubuntu and instead returns debian. # Or at least it does in some build environments like Travis CI return "ubuntu" else: raise RuntimeError("This module is not supported on {}." .format(current_platform))
python
def get_platform(): """Return the current OS platform. For example: if current os platform is Ubuntu then a string "ubuntu" will be returned (which is the name of the module). This string is used to decide which platform module should be imported. """ # 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_platform: return "centos" elif "debian" in current_platform: # Stock Python does not detect Ubuntu and instead returns debian. # Or at least it does in some build environments like Travis CI return "ubuntu" else: raise RuntimeError("This module is not supported on {}." .format(current_platform))
[ "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_platform", ":", "return", "\"centos\"", "elif", "\"debian\"", "in", "current_platform", ":", "# Stock Python does not detect Ubuntu and instead returns debian.", "# Or at least it does in some build environments like Travis CI", "return", "\"ubuntu\"", "else", ":", "raise", "RuntimeError", "(", "\"This module is not supported on {}.\"", ".", "format", "(", "current_platform", ")", ")" ]
Return the current OS platform. For example: if current os platform is Ubuntu then a string "ubuntu" will be returned (which is the name of the module). This string is used to decide which platform module should be imported.
[ "Return", "the", "current", "OS", "platform", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/osplatform.py#L4-L25
train
juju/charm-helpers
charmhelpers/fetch/python/version.py
current_version_string
def current_version_string(): """Current system python version as string major.minor.micro""" return "{0}.{1}.{2}".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
python
def current_version_string(): """Current system python version as string major.minor.micro""" return "{0}.{1}.{2}".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
[ "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
[ "Current", "system", "python", "version", "as", "string", "major", ".", "minor", ".", "micro" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/version.py#L28-L32
train
juju/charm-helpers
charmhelpers/contrib/hardening/mysql/checks/config.py
get_audits
def get_audits(): """Get MySQL hardening config audits. :returns: dictionary of 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 = hardening_settings['mysql-conf'] audits = [ FilePermissionAudit(paths=[my_cnf], user='root', group='root', mode=0o0600), TemplatedFile(hardening_settings['hardening-conf'], MySQLConfContext(), TEMPLATES_DIR, mode=0o0750, user='mysql', group='root', service_actions=[{'service': 'mysql', 'actions': ['restart']}]), # MySQL and Percona charms do not allow configuration of the # data directory, so use the default. DirectoryPermissionAudit('/var/lib/mysql', user='mysql', group='mysql', recursive=False, mode=0o755), DirectoryPermissionAudit('/etc/mysql', user='root', group='root', recursive=False, mode=0o700), ] return audits
python
def get_audits(): """Get MySQL hardening config audits. :returns: dictionary of 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 = hardening_settings['mysql-conf'] audits = [ FilePermissionAudit(paths=[my_cnf], user='root', group='root', mode=0o0600), TemplatedFile(hardening_settings['hardening-conf'], MySQLConfContext(), TEMPLATES_DIR, mode=0o0750, user='mysql', group='root', service_actions=[{'service': 'mysql', 'actions': ['restart']}]), # MySQL and Percona charms do not allow configuration of the # data directory, so use the default. DirectoryPermissionAudit('/var/lib/mysql', user='mysql', group='mysql', recursive=False, mode=0o755), DirectoryPermissionAudit('/etc/mysql', user='root', group='root', recursive=False, mode=0o700), ] return audits
[ "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", "=", "hardening_settings", "[", "'mysql-conf'", "]", "audits", "=", "[", "FilePermissionAudit", "(", "paths", "=", "[", "my_cnf", "]", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ",", "mode", "=", "0o0600", ")", ",", "TemplatedFile", "(", "hardening_settings", "[", "'hardening-conf'", "]", ",", "MySQLConfContext", "(", ")", ",", "TEMPLATES_DIR", ",", "mode", "=", "0o0750", ",", "user", "=", "'mysql'", ",", "group", "=", "'root'", ",", "service_actions", "=", "[", "{", "'service'", ":", "'mysql'", ",", "'actions'", ":", "[", "'restart'", "]", "}", "]", ")", ",", "# MySQL and Percona charms do not allow configuration of the", "# data directory, so use the default.", "DirectoryPermissionAudit", "(", "'/var/lib/mysql'", ",", "user", "=", "'mysql'", ",", "group", "=", "'mysql'", ",", "recursive", "=", "False", ",", "mode", "=", "0o755", ")", ",", "DirectoryPermissionAudit", "(", "'/etc/mysql'", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ",", "recursive", "=", "False", ",", "mode", "=", "0o700", ")", ",", "]", "return", "audits" ]
Get MySQL hardening config audits. :returns: dictionary of audits
[ "Get", "MySQL", "hardening", "config", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/mysql/checks/config.py#L31-L73
train
juju/charm-helpers
charmhelpers/core/host.py
service_reload
def service_reload(service_name, restart_on_failure=False, **kwargs): """Reload a system service, optionally falling back to restart if reload fails. The specified service name is managed via the system level init system. Some init systems (e.g. upstart) require that additional arguments be provided in order to directly control service instances whereas other init systems allow for addressing instances of a service directly by name (e.g. systemd). The kwargs allow for the additional parameters to be passed to underlying init systems for those systems which require/allow for them. For example, the ceph-osd upstart script requires the id parameter to be passed along in order to identify which running daemon should be reloaded. The follow- ing example restarts the ceph-osd service for instance id=4: service_reload('ceph-osd', id=4) :param service_name: the name of the service to reload :param restart_on_failure: boolean indicating whether to fallback to a restart if the reload fails. :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems not allowing additional parameters via the commandline (systemd). """ 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
python
def service_reload(service_name, restart_on_failure=False, **kwargs): """Reload a system service, optionally falling back to restart if reload fails. The specified service name is managed via the system level init system. Some init systems (e.g. upstart) require that additional arguments be provided in order to directly control service instances whereas other init systems allow for addressing instances of a service directly by name (e.g. systemd). The kwargs allow for the additional parameters to be passed to underlying init systems for those systems which require/allow for them. For example, the ceph-osd upstart script requires the id parameter to be passed along in order to identify which running daemon should be reloaded. The follow- ing example restarts the ceph-osd service for instance id=4: service_reload('ceph-osd', id=4) :param service_name: the name of the service to reload :param restart_on_failure: boolean indicating whether to fallback to a restart if the reload fails. :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems not allowing additional parameters via the commandline (systemd). """ 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
[ "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. The specified service name is managed via the system level init system. Some init systems (e.g. upstart) require that additional arguments be provided in order to directly control service instances whereas other init systems allow for addressing instances of a service directly by name (e.g. systemd). The kwargs allow for the additional parameters to be passed to underlying init systems for those systems which require/allow for them. For example, the ceph-osd upstart script requires the id parameter to be passed along in order to identify which running daemon should be reloaded. The follow- ing example restarts the ceph-osd service for instance id=4: service_reload('ceph-osd', id=4) :param service_name: the name of the service to reload :param restart_on_failure: boolean indicating whether to fallback to a restart if the reload fails. :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems not allowing additional parameters via the commandline (systemd).
[ "Reload", "a", "system", "service", "optionally", "falling", "back", "to", "restart", "if", "reload", "fails", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L143-L173
train
juju/charm-helpers
charmhelpers/core/host.py
service_pause
def service_pause(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): """Pause a system service. Stop it, and prevent it from starting again at boot. :param service_name: the name of the service to pause :param init_dir: path to the upstart init directory :param initd_dir: path to the sysv init directory :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems which do not support key=value arguments via the commandline. """ 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.path.join(initd_dir, service_name) if init_is_systemd(): service('disable', service_name) service('mask', service_name) elif os.path.exists(upstart_file): override_path = os.path.join( init_dir, '{}.override'.format(service_name)) with open(override_path, 'w') as fh: fh.write("manual\n") elif os.path.exists(sysv_file): subprocess.check_call(["update-rc.d", service_name, "disable"]) else: raise ValueError( "Unable to detect {0} as SystemD, Upstart {1} or" " SysV {2}".format( service_name, upstart_file, sysv_file)) return stopped
python
def service_pause(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): """Pause a system service. Stop it, and prevent it from starting again at boot. :param service_name: the name of the service to pause :param init_dir: path to the upstart init directory :param initd_dir: path to the sysv init directory :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems which do not support key=value arguments via the commandline. """ 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.path.join(initd_dir, service_name) if init_is_systemd(): service('disable', service_name) service('mask', service_name) elif os.path.exists(upstart_file): override_path = os.path.join( init_dir, '{}.override'.format(service_name)) with open(override_path, 'w') as fh: fh.write("manual\n") elif os.path.exists(sysv_file): subprocess.check_call(["update-rc.d", service_name, "disable"]) else: raise ValueError( "Unable to detect {0} as SystemD, Upstart {1} or" " SysV {2}".format( service_name, upstart_file, sysv_file)) return stopped
[ "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", ".", "path", ".", "join", "(", "initd_dir", ",", "service_name", ")", "if", "init_is_systemd", "(", ")", ":", "service", "(", "'disable'", ",", "service_name", ")", "service", "(", "'mask'", ",", "service_name", ")", "elif", "os", ".", "path", ".", "exists", "(", "upstart_file", ")", ":", "override_path", "=", "os", ".", "path", ".", "join", "(", "init_dir", ",", "'{}.override'", ".", "format", "(", "service_name", ")", ")", "with", "open", "(", "override_path", ",", "'w'", ")", "as", "fh", ":", "fh", ".", "write", "(", "\"manual\\n\"", ")", "elif", "os", ".", "path", ".", "exists", "(", "sysv_file", ")", ":", "subprocess", ".", "check_call", "(", "[", "\"update-rc.d\"", ",", "service_name", ",", "\"disable\"", "]", ")", "else", ":", "raise", "ValueError", "(", "\"Unable to detect {0} as SystemD, Upstart {1} or\"", "\" SysV {2}\"", ".", "format", "(", "service_name", ",", "upstart_file", ",", "sysv_file", ")", ")", "return", "stopped" ]
Pause a system service. Stop it, and prevent it from starting again at boot. :param service_name: the name of the service to pause :param init_dir: path to the upstart init directory :param initd_dir: path to the sysv init directory :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems which do not support key=value arguments via the commandline.
[ "Pause", "a", "system", "service", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L176-L211
train
juju/charm-helpers
charmhelpers/core/host.py
service_resume
def service_resume(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): """Resume a system service. Reenable starting again at boot. Start the service. :param service_name: the name of the service to resume :param init_dir: the path to the init dir :param initd dir: the path to the initd dir :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for systemd enabled systems. """ 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('enable', service_name) elif os.path.exists(upstart_file): override_path = os.path.join( init_dir, '{}.override'.format(service_name)) if os.path.exists(override_path): os.unlink(override_path) elif os.path.exists(sysv_file): subprocess.check_call(["update-rc.d", service_name, "enable"]) else: raise ValueError( "Unable to detect {0} as SystemD, Upstart {1} or" " SysV {2}".format( service_name, upstart_file, sysv_file)) started = service_running(service_name, **kwargs) if not started: started = service_start(service_name, **kwargs) return started
python
def service_resume(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): """Resume a system service. Reenable starting again at boot. Start the service. :param service_name: the name of the service to resume :param init_dir: the path to the init dir :param initd dir: the path to the initd dir :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for systemd enabled systems. """ 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('enable', service_name) elif os.path.exists(upstart_file): override_path = os.path.join( init_dir, '{}.override'.format(service_name)) if os.path.exists(override_path): os.unlink(override_path) elif os.path.exists(sysv_file): subprocess.check_call(["update-rc.d", service_name, "enable"]) else: raise ValueError( "Unable to detect {0} as SystemD, Upstart {1} or" " SysV {2}".format( service_name, upstart_file, sysv_file)) started = service_running(service_name, **kwargs) if not started: started = service_start(service_name, **kwargs) return started
[ "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", "(", "'enable'", ",", "service_name", ")", "elif", "os", ".", "path", ".", "exists", "(", "upstart_file", ")", ":", "override_path", "=", "os", ".", "path", ".", "join", "(", "init_dir", ",", "'{}.override'", ".", "format", "(", "service_name", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "override_path", ")", ":", "os", ".", "unlink", "(", "override_path", ")", "elif", "os", ".", "path", ".", "exists", "(", "sysv_file", ")", ":", "subprocess", ".", "check_call", "(", "[", "\"update-rc.d\"", ",", "service_name", ",", "\"enable\"", "]", ")", "else", ":", "raise", "ValueError", "(", "\"Unable to detect {0} as SystemD, Upstart {1} or\"", "\" SysV {2}\"", ".", "format", "(", "service_name", ",", "upstart_file", ",", "sysv_file", ")", ")", "started", "=", "service_running", "(", "service_name", ",", "*", "*", "kwargs", ")", "if", "not", "started", ":", "started", "=", "service_start", "(", "service_name", ",", "*", "*", "kwargs", ")", "return", "started" ]
Resume a system service. Reenable starting again at boot. Start the service. :param service_name: the name of the service to resume :param init_dir: the path to the init dir :param initd dir: the path to the initd dir :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for systemd enabled systems.
[ "Resume", "a", "system", "service", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L214-L249
train
juju/charm-helpers
charmhelpers/core/host.py
service
def service(action, service_name, **kwargs): """Control a system service. :param action: the action to take on the service :param service_name: the name of the service to perform th action on :param **kwargs: additional params to be passed to the service command in the form of key=value. """ 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) == 0
python
def service(action, service_name, **kwargs): """Control a system service. :param action: the action to take on the service :param service_name: the name of the service to perform th action on :param **kwargs: additional params to be passed to the service command in the form of key=value. """ 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) == 0
[ "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", ")", "==", "0" ]
Control a system service. :param action: the action to take on the service :param service_name: the name of the service to perform th action on :param **kwargs: additional params to be passed to the service command in the form of key=value.
[ "Control", "a", "system", "service", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L252-L267
train
juju/charm-helpers
charmhelpers/core/host.py
service_running
def service_running(service_name, **kwargs): """Determine whether a system service is running. :param service_name: the name of the service :param **kwargs: additional args to pass to the service command. This is used to pass additional key=value arguments to the service command line for managing specific instance units (e.g. service ceph-osd status id=2). The kwargs are ignored in systemd services. """ 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) cmd.append(parameter) output = subprocess.check_output( cmd, stderr=subprocess.STDOUT).decode('UTF-8') except subprocess.CalledProcessError: return False else: # This works for upstart scripts where the 'service' command # returns a consistent string to represent running # 'start/running' if ("start/running" in output or "is running" in output or "up and running" in output): return True elif os.path.exists(_INIT_D_CONF.format(service_name)): # Check System V scripts init script return codes return service('status', service_name) return False
python
def service_running(service_name, **kwargs): """Determine whether a system service is running. :param service_name: the name of the service :param **kwargs: additional args to pass to the service command. This is used to pass additional key=value arguments to the service command line for managing specific instance units (e.g. service ceph-osd status id=2). The kwargs are ignored in systemd services. """ 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) cmd.append(parameter) output = subprocess.check_output( cmd, stderr=subprocess.STDOUT).decode('UTF-8') except subprocess.CalledProcessError: return False else: # This works for upstart scripts where the 'service' command # returns a consistent string to represent running # 'start/running' if ("start/running" in output or "is running" in output or "up and running" in output): return True elif os.path.exists(_INIT_D_CONF.format(service_name)): # Check System V scripts init script return codes return service('status', service_name) return False
[ "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", ")", "cmd", ".", "append", "(", "parameter", ")", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ".", "decode", "(", "'UTF-8'", ")", "except", "subprocess", ".", "CalledProcessError", ":", "return", "False", "else", ":", "# This works for upstart scripts where the 'service' command", "# returns a consistent string to represent running", "# 'start/running'", "if", "(", "\"start/running\"", "in", "output", "or", "\"is running\"", "in", "output", "or", "\"up and running\"", "in", "output", ")", ":", "return", "True", "elif", "os", ".", "path", ".", "exists", "(", "_INIT_D_CONF", ".", "format", "(", "service_name", ")", ")", ":", "# Check System V scripts init script return codes", "return", "service", "(", "'status'", ",", "service_name", ")", "return", "False" ]
Determine whether a system service is running. :param service_name: the name of the service :param **kwargs: additional args to pass to the service command. This is used to pass additional key=value arguments to the service command line for managing specific instance units (e.g. service ceph-osd status id=2). The kwargs are ignored in systemd services.
[ "Determine", "whether", "a", "system", "service", "is", "running", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L274-L308
train
juju/charm-helpers
charmhelpers/core/host.py
adduser
def adduser(username, password=None, shell='/bin/bash', system_user=False, primary_group=None, secondary_groups=None, uid=None, home_dir=None): """Add a user to the system. Will log but otherwise succeed if the user already exists. :param str username: Username to create :param str password: Password for user; if ``None``, create a system user :param str shell: The default shell for the user :param bool system_user: Whether to create a login or system user :param str primary_group: Primary group for user; defaults to username :param list secondary_groups: Optional list of additional groups :param int uid: UID for user being created :param str home_dir: Home directory for user :returns: The password database entry struct, as returned by `pwd.getpwnam` """ try: user_info = pwd.getpwnam(username) log('user {0} already exists!'.format(username)) if uid: user_info = pwd.getpwuid(int(uid)) log('user with uid {0} already exists!'.format(uid)) except KeyError: log('creating user {0}'.format(username)) cmd = ['useradd'] if uid: cmd.extend(['--uid', str(uid)]) if home_dir: cmd.extend(['--home', str(home_dir)]) if system_user or password is None: cmd.append('--system') else: cmd.extend([ '--create-home', '--shell', shell, '--password', password, ]) if not primary_group: try: grp.getgrnam(username) primary_group = username # avoid "group exists" error except KeyError: pass if primary_group: cmd.extend(['-g', primary_group]) if secondary_groups: cmd.extend(['-G', ','.join(secondary_groups)]) cmd.append(username) subprocess.check_call(cmd) user_info = pwd.getpwnam(username) return user_info
python
def adduser(username, password=None, shell='/bin/bash', system_user=False, primary_group=None, secondary_groups=None, uid=None, home_dir=None): """Add a user to the system. Will log but otherwise succeed if the user already exists. :param str username: Username to create :param str password: Password for user; if ``None``, create a system user :param str shell: The default shell for the user :param bool system_user: Whether to create a login or system user :param str primary_group: Primary group for user; defaults to username :param list secondary_groups: Optional list of additional groups :param int uid: UID for user being created :param str home_dir: Home directory for user :returns: The password database entry struct, as returned by `pwd.getpwnam` """ try: user_info = pwd.getpwnam(username) log('user {0} already exists!'.format(username)) if uid: user_info = pwd.getpwuid(int(uid)) log('user with uid {0} already exists!'.format(uid)) except KeyError: log('creating user {0}'.format(username)) cmd = ['useradd'] if uid: cmd.extend(['--uid', str(uid)]) if home_dir: cmd.extend(['--home', str(home_dir)]) if system_user or password is None: cmd.append('--system') else: cmd.extend([ '--create-home', '--shell', shell, '--password', password, ]) if not primary_group: try: grp.getgrnam(username) primary_group = username # avoid "group exists" error except KeyError: pass if primary_group: cmd.extend(['-g', primary_group]) if secondary_groups: cmd.extend(['-G', ','.join(secondary_groups)]) cmd.append(username) subprocess.check_call(cmd) user_info = pwd.getpwnam(username) return user_info
[ "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", ")", ")", "log", "(", "'user with uid {0} already exists!'", ".", "format", "(", "uid", ")", ")", "except", "KeyError", ":", "log", "(", "'creating user {0}'", ".", "format", "(", "username", ")", ")", "cmd", "=", "[", "'useradd'", "]", "if", "uid", ":", "cmd", ".", "extend", "(", "[", "'--uid'", ",", "str", "(", "uid", ")", "]", ")", "if", "home_dir", ":", "cmd", ".", "extend", "(", "[", "'--home'", ",", "str", "(", "home_dir", ")", "]", ")", "if", "system_user", "or", "password", "is", "None", ":", "cmd", ".", "append", "(", "'--system'", ")", "else", ":", "cmd", ".", "extend", "(", "[", "'--create-home'", ",", "'--shell'", ",", "shell", ",", "'--password'", ",", "password", ",", "]", ")", "if", "not", "primary_group", ":", "try", ":", "grp", ".", "getgrnam", "(", "username", ")", "primary_group", "=", "username", "# avoid \"group exists\" error", "except", "KeyError", ":", "pass", "if", "primary_group", ":", "cmd", ".", "extend", "(", "[", "'-g'", ",", "primary_group", "]", ")", "if", "secondary_groups", ":", "cmd", ".", "extend", "(", "[", "'-G'", ",", "','", ".", "join", "(", "secondary_groups", ")", "]", ")", "cmd", ".", "append", "(", "username", ")", "subprocess", ".", "check_call", "(", "cmd", ")", "user_info", "=", "pwd", ".", "getpwnam", "(", "username", ")", "return", "user_info" ]
Add a user to the system. Will log but otherwise succeed if the user already exists. :param str username: Username to create :param str password: Password for user; if ``None``, create a system user :param str shell: The default shell for the user :param bool system_user: Whether to create a login or system user :param str primary_group: Primary group for user; defaults to username :param list secondary_groups: Optional list of additional groups :param int uid: UID for user being created :param str home_dir: Home directory for user :returns: The password database entry struct, as returned by `pwd.getpwnam`
[ "Add", "a", "user", "to", "the", "system", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L321-L373
train
juju/charm-helpers
charmhelpers/core/host.py
user_exists
def user_exists(username): """Check if a user exists""" try: pwd.getpwnam(username) user_exists = True except KeyError: user_exists = False return user_exists
python
def user_exists(username): """Check if a user exists""" try: pwd.getpwnam(username) user_exists = True except KeyError: user_exists = False return user_exists
[ "def", "user_exists", "(", "username", ")", ":", "try", ":", "pwd", ".", "getpwnam", "(", "username", ")", "user_exists", "=", "True", "except", "KeyError", ":", "user_exists", "=", "False", "return", "user_exists" ]
Check if a user exists
[ "Check", "if", "a", "user", "exists" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L376-L383
train
juju/charm-helpers
charmhelpers/core/host.py
uid_exists
def uid_exists(uid): """Check if a uid exists""" try: pwd.getpwuid(uid) uid_exists = True except KeyError: uid_exists = False return uid_exists
python
def uid_exists(uid): """Check if a uid exists""" try: pwd.getpwuid(uid) uid_exists = True except KeyError: uid_exists = False return uid_exists
[ "def", "uid_exists", "(", "uid", ")", ":", "try", ":", "pwd", ".", "getpwuid", "(", "uid", ")", "uid_exists", "=", "True", "except", "KeyError", ":", "uid_exists", "=", "False", "return", "uid_exists" ]
Check if a uid exists
[ "Check", "if", "a", "uid", "exists" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L386-L393
train
juju/charm-helpers
charmhelpers/core/host.py
group_exists
def group_exists(groupname): """Check if a group exists""" try: grp.getgrnam(groupname) group_exists = True except KeyError: group_exists = False return group_exists
python
def group_exists(groupname): """Check if a group exists""" try: grp.getgrnam(groupname) group_exists = True except KeyError: group_exists = False return group_exists
[ "def", "group_exists", "(", "groupname", ")", ":", "try", ":", "grp", ".", "getgrnam", "(", "groupname", ")", "group_exists", "=", "True", "except", "KeyError", ":", "group_exists", "=", "False", "return", "group_exists" ]
Check if a group exists
[ "Check", "if", "a", "group", "exists" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L396-L403
train
juju/charm-helpers
charmhelpers/core/host.py
gid_exists
def gid_exists(gid): """Check if a gid exists""" try: grp.getgrgid(gid) gid_exists = True except KeyError: gid_exists = False return gid_exists
python
def gid_exists(gid): """Check if a gid exists""" try: grp.getgrgid(gid) gid_exists = True except KeyError: gid_exists = False return gid_exists
[ "def", "gid_exists", "(", "gid", ")", ":", "try", ":", "grp", ".", "getgrgid", "(", "gid", ")", "gid_exists", "=", "True", "except", "KeyError", ":", "gid_exists", "=", "False", "return", "gid_exists" ]
Check if a gid exists
[ "Check", "if", "a", "gid", "exists" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L406-L413
train
juju/charm-helpers
charmhelpers/core/host.py
add_group
def add_group(group_name, system_group=False, gid=None): """Add a group to the system Will log but otherwise succeed if the group already exists. :param str group_name: group to create :param bool system_group: Create system group :param int gid: GID for user being created :returns: The password database entry struct, as returned by `grp.getgrnam` """ 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 group {0}'.format(group_name)) add_new_group(group_name, system_group, gid) group_info = grp.getgrnam(group_name) return group_info
python
def add_group(group_name, system_group=False, gid=None): """Add a group to the system Will log but otherwise succeed if the group already exists. :param str group_name: group to create :param bool system_group: Create system group :param int gid: GID for user being created :returns: The password database entry struct, as returned by `grp.getgrnam` """ 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 group {0}'.format(group_name)) add_new_group(group_name, system_group, gid) group_info = grp.getgrnam(group_name) return group_info
[ "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 group {0}'", ".", "format", "(", "group_name", ")", ")", "add_new_group", "(", "group_name", ",", "system_group", ",", "gid", ")", "group_info", "=", "grp", ".", "getgrnam", "(", "group_name", ")", "return", "group_info" ]
Add a group to the system Will log but otherwise succeed if the group already exists. :param str group_name: group to create :param bool system_group: Create system group :param int gid: GID for user being created :returns: The password database entry struct, as returned by `grp.getgrnam`
[ "Add", "a", "group", "to", "the", "system" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L416-L437
train
juju/charm-helpers
charmhelpers/core/host.py
chage
def chage(username, lastday=None, expiredate=None, inactive=None, mindays=None, maxdays=None, root=None, warndays=None): """Change user password expiry information :param str username: User to update :param str lastday: Set when password was changed in YYYY-MM-DD format :param str expiredate: Set when user's account will no longer be accessible in YYYY-MM-DD format. -1 will remove an account expiration date. :param str inactive: Set the number of days of inactivity after a password has expired before the account is locked. -1 will remove an account's inactivity. :param str mindays: Set the minimum number of days between password changes to MIN_DAYS. 0 indicates the password can be changed anytime. :param str maxdays: Set the maximum number of days during which a password is valid. -1 as MAX_DAYS will remove checking maxdays :param str root: Apply changes in the CHROOT_DIR directory :param str warndays: Set the number of days of warning before a password change is required :raises subprocess.CalledProcessError: if call to chage fails """ cmd = ['chage'] if root: cmd.extend(['--root', root]) if lastday: cmd.extend(['--lastday', lastday]) if expiredate: cmd.extend(['--expiredate', expiredate]) if inactive: cmd.extend(['--inactive', inactive]) if mindays: cmd.extend(['--mindays', mindays]) if maxdays: cmd.extend(['--maxdays', maxdays]) if warndays: cmd.extend(['--warndays', warndays]) cmd.append(username) subprocess.check_call(cmd)
python
def chage(username, lastday=None, expiredate=None, inactive=None, mindays=None, maxdays=None, root=None, warndays=None): """Change user password expiry information :param str username: User to update :param str lastday: Set when password was changed in YYYY-MM-DD format :param str expiredate: Set when user's account will no longer be accessible in YYYY-MM-DD format. -1 will remove an account expiration date. :param str inactive: Set the number of days of inactivity after a password has expired before the account is locked. -1 will remove an account's inactivity. :param str mindays: Set the minimum number of days between password changes to MIN_DAYS. 0 indicates the password can be changed anytime. :param str maxdays: Set the maximum number of days during which a password is valid. -1 as MAX_DAYS will remove checking maxdays :param str root: Apply changes in the CHROOT_DIR directory :param str warndays: Set the number of days of warning before a password change is required :raises subprocess.CalledProcessError: if call to chage fails """ cmd = ['chage'] if root: cmd.extend(['--root', root]) if lastday: cmd.extend(['--lastday', lastday]) if expiredate: cmd.extend(['--expiredate', expiredate]) if inactive: cmd.extend(['--inactive', inactive]) if mindays: cmd.extend(['--mindays', mindays]) if maxdays: cmd.extend(['--maxdays', maxdays]) if warndays: cmd.extend(['--warndays', warndays]) cmd.append(username) subprocess.check_call(cmd)
[ "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'", ",", "expiredate", "]", ")", "if", "inactive", ":", "cmd", ".", "extend", "(", "[", "'--inactive'", ",", "inactive", "]", ")", "if", "mindays", ":", "cmd", ".", "extend", "(", "[", "'--mindays'", ",", "mindays", "]", ")", "if", "maxdays", ":", "cmd", ".", "extend", "(", "[", "'--maxdays'", ",", "maxdays", "]", ")", "if", "warndays", ":", "cmd", ".", "extend", "(", "[", "'--warndays'", ",", "warndays", "]", ")", "cmd", ".", "append", "(", "username", ")", "subprocess", ".", "check_call", "(", "cmd", ")" ]
Change user password expiry information :param str username: User to update :param str lastday: Set when password was changed in YYYY-MM-DD format :param str expiredate: Set when user's account will no longer be accessible in YYYY-MM-DD format. -1 will remove an account expiration date. :param str inactive: Set the number of days of inactivity after a password has expired before the account is locked. -1 will remove an account's inactivity. :param str mindays: Set the minimum number of days between password changes to MIN_DAYS. 0 indicates the password can be changed anytime. :param str maxdays: Set the maximum number of days during which a password is valid. -1 as MAX_DAYS will remove checking maxdays :param str root: Apply changes in the CHROOT_DIR directory :param str warndays: Set the number of days of warning before a password change is required :raises subprocess.CalledProcessError: if call to chage fails
[ "Change", "user", "password", "expiry", "information" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L447-L486
train
juju/charm-helpers
charmhelpers/core/host.py
rsync
def rsync(from_path, to_path, flags='-r', options=None, timeout=None): """Replicate the contents of a path""" 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(" ".join(cmd)) return subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('UTF-8').strip()
python
def rsync(from_path, to_path, flags='-r', options=None, timeout=None): """Replicate the contents of a path""" 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(" ".join(cmd)) return subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('UTF-8').strip()
[ "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", "(", "\" \"", ".", "join", "(", "cmd", ")", ")", "return", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ".", "decode", "(", "'UTF-8'", ")", ".", "strip", "(", ")" ]
Replicate the contents of a path
[ "Replicate", "the", "contents", "of", "a", "path" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L492-L502
train
juju/charm-helpers
charmhelpers/core/host.py
write_file
def write_file(path, content, owner='root', group='root', perms=0o444): """Create or overwrite a file with the contents of a byte string.""" 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 = None, None, None try: with open(path, 'rb') as target: existing_content = target.read() stat = os.stat(path) existing_uid, existing_gid, existing_perms = ( stat.st_uid, stat.st_gid, stat.st_mode ) except Exception: pass if content != existing_content: log("Writing file {} {}:{} {:o}".format(path, owner, group, perms), level=DEBUG) with open(path, 'wb') as target: os.fchown(target.fileno(), uid, gid) os.fchmod(target.fileno(), perms) if six.PY3 and isinstance(content, six.string_types): content = content.encode('UTF-8') target.write(content) return # the contents were the same, but we might still need to change the # ownership or permissions. if existing_uid != uid: log("Changing uid on already existing content: {} -> {}" .format(existing_uid, uid), level=DEBUG) os.chown(path, uid, -1) if existing_gid != gid: log("Changing gid on already existing content: {} -> {}" .format(existing_gid, gid), level=DEBUG) os.chown(path, -1, gid) if existing_perms != perms: log("Changing permissions on existing content: {} -> {}" .format(existing_perms, perms), level=DEBUG) os.chmod(path, perms)
python
def write_file(path, content, owner='root', group='root', perms=0o444): """Create or overwrite a file with the contents of a byte string.""" 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 = None, None, None try: with open(path, 'rb') as target: existing_content = target.read() stat = os.stat(path) existing_uid, existing_gid, existing_perms = ( stat.st_uid, stat.st_gid, stat.st_mode ) except Exception: pass if content != existing_content: log("Writing file {} {}:{} {:o}".format(path, owner, group, perms), level=DEBUG) with open(path, 'wb') as target: os.fchown(target.fileno(), uid, gid) os.fchmod(target.fileno(), perms) if six.PY3 and isinstance(content, six.string_types): content = content.encode('UTF-8') target.write(content) return # the contents were the same, but we might still need to change the # ownership or permissions. if existing_uid != uid: log("Changing uid on already existing content: {} -> {}" .format(existing_uid, uid), level=DEBUG) os.chown(path, uid, -1) if existing_gid != gid: log("Changing gid on already existing content: {} -> {}" .format(existing_gid, gid), level=DEBUG) os.chown(path, -1, gid) if existing_perms != perms: log("Changing permissions on existing content: {} -> {}" .format(existing_perms, perms), level=DEBUG) os.chmod(path, perms)
[ "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", "=", "None", ",", "None", ",", "None", "try", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "target", ":", "existing_content", "=", "target", ".", "read", "(", ")", "stat", "=", "os", ".", "stat", "(", "path", ")", "existing_uid", ",", "existing_gid", ",", "existing_perms", "=", "(", "stat", ".", "st_uid", ",", "stat", ".", "st_gid", ",", "stat", ".", "st_mode", ")", "except", "Exception", ":", "pass", "if", "content", "!=", "existing_content", ":", "log", "(", "\"Writing file {} {}:{} {:o}\"", ".", "format", "(", "path", ",", "owner", ",", "group", ",", "perms", ")", ",", "level", "=", "DEBUG", ")", "with", "open", "(", "path", ",", "'wb'", ")", "as", "target", ":", "os", ".", "fchown", "(", "target", ".", "fileno", "(", ")", ",", "uid", ",", "gid", ")", "os", ".", "fchmod", "(", "target", ".", "fileno", "(", ")", ",", "perms", ")", "if", "six", ".", "PY3", "and", "isinstance", "(", "content", ",", "six", ".", "string_types", ")", ":", "content", "=", "content", ".", "encode", "(", "'UTF-8'", ")", "target", ".", "write", "(", "content", ")", "return", "# the contents were the same, but we might still need to change the", "# ownership or permissions.", "if", "existing_uid", "!=", "uid", ":", "log", "(", "\"Changing uid on already existing content: {} -> {}\"", ".", "format", "(", "existing_uid", ",", "uid", ")", ",", "level", "=", "DEBUG", ")", "os", ".", "chown", "(", "path", ",", "uid", ",", "-", "1", ")", "if", "existing_gid", "!=", "gid", ":", "log", "(", "\"Changing gid on already existing content: {} -> {}\"", ".", "format", "(", "existing_gid", ",", "gid", ")", ",", "level", "=", "DEBUG", ")", "os", ".", "chown", "(", "path", ",", "-", "1", ",", "gid", ")", "if", "existing_perms", "!=", "perms", ":", "log", "(", "\"Changing permissions on existing content: {} -> {}\"", ".", "format", "(", "existing_perms", ",", "perms", ")", ",", "level", "=", "DEBUG", ")", "os", ".", "chmod", "(", "path", ",", "perms", ")" ]
Create or overwrite a file with the contents of a byte string.
[ "Create", "or", "overwrite", "a", "file", "with", "the", "contents", "of", "a", "byte", "string", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L536-L576
train
juju/charm-helpers
charmhelpers/core/host.py
mount
def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): """Mount a filesystem at a particular mountpoint""" 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: log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) return False if persist: return fstab_add(device, mountpoint, filesystem, options=options) return True
python
def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): """Mount a filesystem at a particular mountpoint""" 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: log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) return False if persist: return fstab_add(device, mountpoint, filesystem, options=options) return True
[ "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", ":", "log", "(", "'Error mounting {} at {}\\n{}'", ".", "format", "(", "device", ",", "mountpoint", ",", "e", ".", "output", ")", ")", "return", "False", "if", "persist", ":", "return", "fstab_add", "(", "device", ",", "mountpoint", ",", "filesystem", ",", "options", "=", "options", ")", "return", "True" ]
Mount a filesystem at a particular mountpoint
[ "Mount", "a", "filesystem", "at", "a", "particular", "mountpoint" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L589-L603
train
juju/charm-helpers
charmhelpers/core/host.py
umount
def umount(mountpoint, persist=False): """Unmount a filesystem""" 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
python
def umount(mountpoint, persist=False): """Unmount a filesystem""" 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
[ "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
[ "Unmount", "a", "filesystem" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L606-L617
train
juju/charm-helpers
charmhelpers/core/host.py
fstab_mount
def fstab_mount(mountpoint): """Mount filesystem using fstab""" 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
python
def fstab_mount(mountpoint): """Mount filesystem using fstab""" 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
[ "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
[ "Mount", "filesystem", "using", "fstab" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L629-L637
train
juju/charm-helpers
charmhelpers/core/host.py
file_hash
def file_hash(path, hash_type='md5'): """Generate a hash checksum of the contents of 'path' or None if not found. :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. """ 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
python
def file_hash(path, hash_type='md5'): """Generate a hash checksum of the contents of 'path' or None if not found. :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. """ 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
[ "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. :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc.
[ "Generate", "a", "hash", "checksum", "of", "the", "contents", "of", "path", "or", "None", "if", "not", "found", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L640-L652
train
juju/charm-helpers
charmhelpers/core/host.py
check_hash
def check_hash(path, checksum, hash_type='md5'): """Validate a file using a cryptographic checksum. :param str checksum: Value of the checksum used to validate the file. :param str hash_type: Hash algorithm used to generate `checksum`. Can be any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. :raises ChecksumError: If the file fails the checksum """ actual_checksum = file_hash(path, hash_type) if checksum != actual_checksum: raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum))
python
def check_hash(path, checksum, hash_type='md5'): """Validate a file using a cryptographic checksum. :param str checksum: Value of the checksum used to validate the file. :param str hash_type: Hash algorithm used to generate `checksum`. Can be any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. :raises ChecksumError: If the file fails the checksum """ actual_checksum = file_hash(path, hash_type) if checksum != actual_checksum: raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum))
[ "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. :param str checksum: Value of the checksum used to validate the file. :param str hash_type: Hash algorithm used to generate `checksum`. Can be any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. :raises ChecksumError: If the file fails the checksum
[ "Validate", "a", "file", "using", "a", "cryptographic", "checksum", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L669-L681
train
juju/charm-helpers
charmhelpers/core/host.py
restart_on_change
def restart_on_change(restart_map, stopstart=False, restart_functions=None): """Restart services based on configuration files changing This function is used a decorator, for example:: @restart_on_change({ '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] '/etc/apache/sites-enabled/*': [ 'apache2' ] }) def config_changed(): pass # your code here In this example, the cinder-api and cinder-volume services would be restarted if /etc/ceph/ceph.conf is changed by the ceph_client_changed function. The apache2 service would be restarted if any file matching the pattern got changed, created or removed. Standard wildcards are supported, see documentation for the 'glob' module for more information. @param restart_map: {path_file_name: [service_name, ...] @param stopstart: DEFAULT false; whether to stop, start OR restart @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result from decorated function """ 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
python
def restart_on_change(restart_map, stopstart=False, restart_functions=None): """Restart services based on configuration files changing This function is used a decorator, for example:: @restart_on_change({ '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] '/etc/apache/sites-enabled/*': [ 'apache2' ] }) def config_changed(): pass # your code here In this example, the cinder-api and cinder-volume services would be restarted if /etc/ceph/ceph.conf is changed by the ceph_client_changed function. The apache2 service would be restarted if any file matching the pattern got changed, created or removed. Standard wildcards are supported, see documentation for the 'glob' module for more information. @param restart_map: {path_file_name: [service_name, ...] @param stopstart: DEFAULT false; whether to stop, start OR restart @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result from decorated function """ 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
[ "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 This function is used a decorator, for example:: @restart_on_change({ '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] '/etc/apache/sites-enabled/*': [ 'apache2' ] }) def config_changed(): pass # your code here In this example, the cinder-api and cinder-volume services would be restarted if /etc/ceph/ceph.conf is changed by the ceph_client_changed function. The apache2 service would be restarted if any file matching the pattern got changed, created or removed. Standard wildcards are supported, see documentation for the 'glob' module for more information. @param restart_map: {path_file_name: [service_name, ...] @param stopstart: DEFAULT false; whether to stop, start OR restart @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result from decorated function
[ "Restart", "services", "based", "on", "configuration", "files", "changing" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L689-L721
train
juju/charm-helpers
charmhelpers/core/host.py
restart_on_change_helper
def restart_on_change_helper(lambda_f, restart_map, stopstart=False, restart_functions=None): """Helper function to perform the restart_on_change function. This is provided for decorators to restart services if files described in the restart_map have changed after an invocation of lambda_f(). @param lambda_f: function to call. @param restart_map: {file: [service, ...]} @param stopstart: whether to stop, start or restart a service @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result of lambda_f() """ 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[path] for path in restart_map if path_hash(path) != checksums[path]] # create a flat list of ordered services without duplicates from lists services_list = list(OrderedDict.fromkeys(itertools.chain(*restarts))) if services_list: actions = ('stop', 'start') if stopstart else ('restart',) for service_name in services_list: if service_name in restart_functions: restart_functions[service_name](service_name) else: for action in actions: service(action, service_name) return r
python
def restart_on_change_helper(lambda_f, restart_map, stopstart=False, restart_functions=None): """Helper function to perform the restart_on_change function. This is provided for decorators to restart services if files described in the restart_map have changed after an invocation of lambda_f(). @param lambda_f: function to call. @param restart_map: {file: [service, ...]} @param stopstart: whether to stop, start or restart a service @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result of lambda_f() """ 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[path] for path in restart_map if path_hash(path) != checksums[path]] # create a flat list of ordered services without duplicates from lists services_list = list(OrderedDict.fromkeys(itertools.chain(*restarts))) if services_list: actions = ('stop', 'start') if stopstart else ('restart',) for service_name in services_list: if service_name in restart_functions: restart_functions[service_name](service_name) else: for action in actions: service(action, service_name) return r
[ "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", "[", "path", "]", "for", "path", "in", "restart_map", "if", "path_hash", "(", "path", ")", "!=", "checksums", "[", "path", "]", "]", "# create a flat list of ordered services without duplicates from lists", "services_list", "=", "list", "(", "OrderedDict", ".", "fromkeys", "(", "itertools", ".", "chain", "(", "*", "restarts", ")", ")", ")", "if", "services_list", ":", "actions", "=", "(", "'stop'", ",", "'start'", ")", "if", "stopstart", "else", "(", "'restart'", ",", ")", "for", "service_name", "in", "services_list", ":", "if", "service_name", "in", "restart_functions", ":", "restart_functions", "[", "service_name", "]", "(", "service_name", ")", "else", ":", "for", "action", "in", "actions", ":", "service", "(", "action", ",", "service_name", ")", "return", "r" ]
Helper function to perform the restart_on_change function. This is provided for decorators to restart services if files described in the restart_map have changed after an invocation of lambda_f(). @param lambda_f: function to call. @param restart_map: {file: [service, ...]} @param stopstart: whether to stop, start or restart a service @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result of lambda_f()
[ "Helper", "function", "to", "perform", "the", "restart_on_change", "function", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L724-L756
train
juju/charm-helpers
charmhelpers/core/host.py
pwgen
def pwgen(length=None): """Generate a random pasword.""" 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 # actual password random_generator = random.SystemRandom() random_chars = [ random_generator.choice(alphanumeric_chars) for _ in range(length)] return(''.join(random_chars))
python
def pwgen(length=None): """Generate a random pasword.""" 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 # actual password random_generator = random.SystemRandom() random_chars = [ random_generator.choice(alphanumeric_chars) for _ in range(length)] return(''.join(random_chars))
[ "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", "# actual password", "random_generator", "=", "random", ".", "SystemRandom", "(", ")", "random_chars", "=", "[", "random_generator", ".", "choice", "(", "alphanumeric_chars", ")", "for", "_", "in", "range", "(", "length", ")", "]", "return", "(", "''", ".", "join", "(", "random_chars", ")", ")" ]
Generate a random pasword.
[ "Generate", "a", "random", "pasword", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L759-L772
train
juju/charm-helpers
charmhelpers/core/host.py
is_phy_iface
def is_phy_iface(interface): """Returns True if interface is not virtual, otherwise False.""" 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
python
def is_phy_iface(interface): """Returns True if interface is not virtual, otherwise False.""" 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
[ "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.
[ "Returns", "True", "if", "interface", "is", "not", "virtual", "otherwise", "False", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L775-L787
train
juju/charm-helpers
charmhelpers/core/host.py
get_bond_master
def get_bond_master(interface): """Returns bond master if interface is bond slave otherwise None. NOTE: the provided interface is expected to be physical """ 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.realpath(master) # make sure it is a bond master if os.path.exists(os.path.join(master, 'bonding')): return os.path.basename(master) return None
python
def get_bond_master(interface): """Returns bond master if interface is bond slave otherwise None. NOTE: the provided interface is expected to be physical """ 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.realpath(master) # make sure it is a bond master if os.path.exists(os.path.join(master, 'bonding')): return os.path.basename(master) return None
[ "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", ".", "realpath", "(", "master", ")", "# make sure it is a bond master", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "master", ",", "'bonding'", ")", ")", ":", "return", "os", ".", "path", ".", "basename", "(", "master", ")", "return", "None" ]
Returns bond master if interface is bond slave otherwise None. NOTE: the provided interface is expected to be physical
[ "Returns", "bond", "master", "if", "interface", "is", "bond", "slave", "otherwise", "None", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L790-L808
train
juju/charm-helpers
charmhelpers/core/host.py
chdir
def chdir(directory): """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. :param str directory: The directory path to change to for this context. """ cur = os.getcwd() try: yield os.chdir(directory) finally: os.chdir(cur)
python
def chdir(directory): """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. :param str directory: The directory path to change to for this context. """ cur = os.getcwd() try: yield os.chdir(directory) finally: os.chdir(cur)
[ "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. :param str directory: The directory path to change to for this context.
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L883-L894
train
juju/charm-helpers
charmhelpers/core/host.py
chownr
def chownr(path, owner, group, follow_links=True, chowntopdir=False): """Recursively change user and group ownership of files and directories in given path. Doesn't chown path itself by default, only its children. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. :param bool follow_links: Also follow and chown links if True :param bool chowntopdir: Also chown path itself if True """ 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(path) if not broken_symlink: chown(path, uid, gid) for root, dirs, files in os.walk(path, followlinks=follow_links): for name in dirs + files: full = os.path.join(root, name) broken_symlink = os.path.lexists(full) and not os.path.exists(full) if not broken_symlink: chown(full, uid, gid)
python
def chownr(path, owner, group, follow_links=True, chowntopdir=False): """Recursively change user and group ownership of files and directories in given path. Doesn't chown path itself by default, only its children. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. :param bool follow_links: Also follow and chown links if True :param bool chowntopdir: Also chown path itself if True """ 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(path) if not broken_symlink: chown(path, uid, gid) for root, dirs, files in os.walk(path, followlinks=follow_links): for name in dirs + files: full = os.path.join(root, name) broken_symlink = os.path.lexists(full) and not os.path.exists(full) if not broken_symlink: chown(full, uid, gid)
[ "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", "(", "path", ")", "if", "not", "broken_symlink", ":", "chown", "(", "path", ",", "uid", ",", "gid", ")", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ",", "followlinks", "=", "follow_links", ")", ":", "for", "name", "in", "dirs", "+", "files", ":", "full", "=", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", "broken_symlink", "=", "os", ".", "path", ".", "lexists", "(", "full", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "full", ")", "if", "not", "broken_symlink", ":", "chown", "(", "full", ",", "uid", ",", "gid", ")" ]
Recursively change user and group ownership of files and directories in given path. Doesn't chown path itself by default, only its children. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. :param bool follow_links: Also follow and chown links if True :param bool chowntopdir: Also chown path itself if True
[ "Recursively", "change", "user", "and", "group", "ownership", "of", "files", "and", "directories", "in", "given", "path", ".", "Doesn", "t", "chown", "path", "itself", "by", "default", "only", "its", "children", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L897-L923
train
juju/charm-helpers
charmhelpers/core/host.py
lchownr
def lchownr(path, owner, group): """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. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. """ chownr(path, owner, group, follow_links=False)
python
def lchownr(path, owner, group): """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. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. """ chownr(path, owner, group, follow_links=False)
[ "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. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid.
[ "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", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L926-L935
train
juju/charm-helpers
charmhelpers/core/host.py
owner
def owner(path): """Returns a tuple containing the username & groupname owning the path. :param str path: the string path to retrieve the ownership :return tuple(str, str): A (username, groupname) tuple containing the name of the user and group owning the path. :raises OSError: if the specified path does not exist """ stat = os.stat(path) username = pwd.getpwuid(stat.st_uid)[0] groupname = grp.getgrgid(stat.st_gid)[0] return username, groupname
python
def owner(path): """Returns a tuple containing the username & groupname owning the path. :param str path: the string path to retrieve the ownership :return tuple(str, str): A (username, groupname) tuple containing the name of the user and group owning the path. :raises OSError: if the specified path does not exist """ stat = os.stat(path) username = pwd.getpwuid(stat.st_uid)[0] groupname = grp.getgrgid(stat.st_gid)[0] return username, groupname
[ "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. :param str path: the string path to retrieve the ownership :return tuple(str, str): A (username, groupname) tuple containing the name of the user and group owning the path. :raises OSError: if the specified path does not exist
[ "Returns", "a", "tuple", "containing", "the", "username", "&", "groupname", "owning", "the", "path", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L938-L949
train
juju/charm-helpers
charmhelpers/core/host.py
get_total_ram
def get_total_ram(): """The total amount of system RAM in bytes. This is what is reported by the OS, and may be overcommitted when there are multiple containers hosted on the same machine. """ 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 # Classic, not KiB. raise NotImplementedError()
python
def get_total_ram(): """The total amount of system RAM in bytes. This is what is reported by the OS, and may be overcommitted when there are multiple containers hosted on the same machine. """ 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 # Classic, not KiB. raise NotImplementedError()
[ "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", "# Classic, not KiB.", "raise", "NotImplementedError", "(", ")" ]
The total amount of system RAM in bytes. This is what is reported by the OS, and may be overcommitted when there are multiple containers hosted on the same machine.
[ "The", "total", "amount", "of", "system", "RAM", "in", "bytes", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L952-L965
train
juju/charm-helpers
charmhelpers/core/host.py
add_to_updatedb_prunepath
def add_to_updatedb_prunepath(path, updatedb_path=UPDATEDB_PATH): """Adds the specified path to the mlocate's udpatedb.conf PRUNEPATH list. This method has no effect if the path specified by updatedb_path does not exist or is not a file. @param path: string the path to add to the updatedb.conf PRUNEPATHS value @param updatedb_path: the path the updatedb.conf file """ if not os.path.exists(updatedb_path) or os.path.isdir(updatedb_path): # If the updatedb.conf file doesn't exist then don't attempt to update # the file as the package providing mlocate may not be installed on # the local system 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(output) f_id.truncate()
python
def add_to_updatedb_prunepath(path, updatedb_path=UPDATEDB_PATH): """Adds the specified path to the mlocate's udpatedb.conf PRUNEPATH list. This method has no effect if the path specified by updatedb_path does not exist or is not a file. @param path: string the path to add to the updatedb.conf PRUNEPATHS value @param updatedb_path: the path the updatedb.conf file """ if not os.path.exists(updatedb_path) or os.path.isdir(updatedb_path): # If the updatedb.conf file doesn't exist then don't attempt to update # the file as the package providing mlocate may not be installed on # the local system 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(output) f_id.truncate()
[ "def", "add_to_updatedb_prunepath", "(", "path", ",", "updatedb_path", "=", "UPDATEDB_PATH", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "updatedb_path", ")", "or", "os", ".", "path", ".", "isdir", "(", "updatedb_path", ")", ":", "# If the updatedb.conf file doesn't exist then don't attempt to update", "# the file as the package providing mlocate may not be installed on", "# the local system", "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", "(", "output", ")", "f_id", ".", "truncate", "(", ")" ]
Adds the specified path to the mlocate's udpatedb.conf PRUNEPATH list. This method has no effect if the path specified by updatedb_path does not exist or is not a file. @param path: string the path to add to the updatedb.conf PRUNEPATHS value @param updatedb_path: the path the updatedb.conf file
[ "Adds", "the", "specified", "path", "to", "the", "mlocate", "s", "udpatedb", ".", "conf", "PRUNEPATH", "list", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L985-L1005
train
juju/charm-helpers
charmhelpers/core/host.py
install_ca_cert
def install_ca_cert(ca_cert, name=None): """ Install the given cert as a trusted CA. The ``name`` is the stem of the filename where the cert is written, and if not provided, it will default to ``juju-{charm_name}``. If the cert is empty or None, or is unchanged, nothing is done. """ 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).hexdigest() if file_hash(cert_file) == new_hash: return log("Installing new CA cert at: {}".format(cert_file), level=INFO) write_file(cert_file, ca_cert) subprocess.check_call(['update-ca-certificates', '--fresh'])
python
def install_ca_cert(ca_cert, name=None): """ Install the given cert as a trusted CA. The ``name`` is the stem of the filename where the cert is written, and if not provided, it will default to ``juju-{charm_name}``. If the cert is empty or None, or is unchanged, nothing is done. """ 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).hexdigest() if file_hash(cert_file) == new_hash: return log("Installing new CA cert at: {}".format(cert_file), level=INFO) write_file(cert_file, ca_cert) subprocess.check_call(['update-ca-certificates', '--fresh'])
[ "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", ")", ".", "hexdigest", "(", ")", "if", "file_hash", "(", "cert_file", ")", "==", "new_hash", ":", "return", "log", "(", "\"Installing new CA cert at: {}\"", ".", "format", "(", "cert_file", ")", ",", "level", "=", "INFO", ")", "write_file", "(", "cert_file", ",", "ca_cert", ")", "subprocess", ".", "check_call", "(", "[", "'update-ca-certificates'", ",", "'--fresh'", "]", ")" ]
Install the given cert as a trusted CA. The ``name`` is the stem of the filename where the cert is written, and if not provided, it will default to ``juju-{charm_name}``. If the cert is empty or None, or is unchanged, nothing is done.
[ "Install", "the", "given", "cert", "as", "a", "trusted", "CA", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L1056-L1077
train
juju/charm-helpers
charmhelpers/contrib/hardening/host/checks/securetty.py
get_audits
def get_audits(): """Get OS hardening Secure TTY audits. :returns: dictionary of audits """ audits = [] audits.append(TemplatedFile('/etc/securetty', SecureTTYContext(), template_dir=TEMPLATES_DIR, mode=0o0400, user='root', group='root')) return audits
python
def get_audits(): """Get OS hardening Secure TTY audits. :returns: dictionary of audits """ audits = [] audits.append(TemplatedFile('/etc/securetty', SecureTTYContext(), template_dir=TEMPLATES_DIR, mode=0o0400, user='root', group='root')) return audits
[ "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. :returns: dictionary of audits
[ "Get", "OS", "hardening", "Secure", "TTY", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/securetty.py#L20-L29
train