def generate_key_pair(key_length=2048): """Create RSA key pair with specified number of bits in key. Returns tuple of private and public keys. """ with tempfiles.tempdir() as tmpdir: keyfile = os.path.join(tmpdir, 'tempkey') args = [ 'ssh-keygen', '-q', # quiet '-N', '', # w/o passphrase '-t', 'rsa', # create key of rsa type '-f', keyfile, # filename of the key file '-C', 'Generated by Sahara' # key comment ] if key_length is not None: args.extend(['-b', key_length]) processutils.execute(*args) if not os.path.exists(keyfile): raise ex.SystemError("Private key file hasn't been created") private_key = open(keyfile).read() public_key_path = keyfile + '.pub' if not os.path.exists(public_key_path): raise ex.SystemError("Public key file hasn't been created") public_key = open(public_key_path).read() return private_key, public_key
def generate_key_pair(key_length=2048): """Create RSA key pair with specified number of bits in key. Returns tuple of private and public keys. """ with tempfiles.tempdir() as tmpdir: keyfile = os.path.join(tmpdir, 'tempkey') # The key is generated in the old PEM format, instead of the native # format of OpenSSH >=6.5, because paramiko does not support it: # https://github.com/paramiko/paramiko/issues/602 args = [ 'ssh-keygen', '-q', # quiet '-N', '', # w/o passphrase '-m', 'PEM', # old PEM format '-t', 'rsa', # create key of rsa type '-f', keyfile, # filename of the key file '-C', 'Generated-by-Sahara' # key comment ] if key_length is not None: args.extend(['-b', key_length]) processutils.execute(*args) if not os.path.exists(keyfile): raise ex.SystemError(_("Private key file hasn't been created")) with open(keyfile) as keyfile_fd: private_key = keyfile_fd.read() public_key_path = keyfile + '.pub' if not os.path.exists(public_key_path): raise ex.SystemError(_("Public key file hasn't been created")) with open(public_key_path) as public_key_path_fd: public_key = public_key_path_fd.read() return private_key, public_key
def url_for(service_catalog, service_type, admin=False, endpoint_type=None): if not endpoint_type: endpoint_type = 'publicURL' if admin: endpoint_type = 'adminURL' service = _get_service_from_catalog(service_catalog, service_type) if service: endpoints = service['endpoints'] if CONF.os_region_name: endpoints = [ e for e in endpoints if e['region'] == CONF.os_region_name ] try: return _get_endpoint_url(endpoints, endpoint_type) except Exception: raise ex.SystemError( _("Endpoint with type %(type)s is not found for service " "%(service)s") % { 'type': endpoint_type, 'service': service_type }) else: raise ex.SystemError( _('Service "%s" not found in service catalog') % service_type)
def _build_proxy_command(self, command, instance=None, port=None, info=None, rootwrap_command=None): # Accepted keywords in the proxy command template: # {host}, {port}, {tenant_id}, {network_id}, {router_id} keywords = {} if not info: info = self.get_neutron_info(instance) keywords['tenant_id'] = context.current().tenant_id keywords['network_id'] = info['network'] # Query Neutron only if needed if '{router_id}' in command: client = neutron.NeutronClient(info['network'], info['uri'], info['token'], info['tenant']) keywords['router_id'] = client.get_router() keywords['host'] = instance.management_ip keywords['port'] = port try: command = command.format(**keywords) except KeyError as e: LOG.error(_('Invalid keyword in proxy_command: %s'), str(e)) # Do not give more details to the end-user raise ex.SystemError('Misconfiguration') if rootwrap_command: command = '{0} {1}'.format(rootwrap_command, command) return command
def send(self, content): try: self.process.stdin.write(content) self.process.stdin.flush() except IOError as e: raise ex.SystemError(e) return len(content)
def get_router(self): matching_router = NeutronClientRemoteWrapper.routers.get( self.network, None) if matching_router: LOG.debug('Returning cached qrouter') return matching_router['id'] routers = self.neutron.list_routers()['routers'] for router in routers: device_id = router['id'] ports = self.neutron.list_ports(device_id=device_id)['ports'] port = next( (port for port in ports if port['network_id'] == self.network), None) if port: matching_router = router NeutronClientRemoteWrapper.routers[ self.network] = matching_router break if not matching_router: raise ex.SystemError( _('Neutron router corresponding to network ' '%s is not found') % self.network) return matching_router['id']
def _check_driver_is_loaded(): if not DRIVER: raise ex.SystemError( _('Remote driver is not loaded. Most probably ' 'you see this error because you are running ' 'Sahara in distributed mode and it is broken.' 'Try running sahara-all instead.'))
def _check_if_active(self, instance): server = nova.get_instance_info(instance) if server.status == 'ERROR': raise exc.SystemError("Node %s has error status" % server.name) return server.status == 'ACTIVE'
def _create_attach_volume(ctx, instance, size, volume_type, name=None, availability_zone=None): if CONF.cinder.api_version == 1: kwargs = {'size': size, 'display_name': name} else: kwargs = {'size': size, 'name': name} kwargs['volume_type'] = volume_type if availability_zone is not None: kwargs['availability_zone'] = availability_zone volume = cinder.client().volumes.create(**kwargs) conductor.append_volume(ctx, instance, volume.id) while volume.status != 'available': volume = cinder.get_volume(volume.id) if volume.status == 'error': raise ex.SystemError(_("Volume %s has error status") % volume.id) context.sleep(1) resp = nova.client().volumes.create_server_volume(instance.instance_id, volume.id, None) return resp.device
def test_check_cinder_exists(self, mock_url_for): mock_url_for.return_value = None self.assertTrue(cinder.check_cinder_exists()) mock_url_for.reset_mock() mock_url_for.side_effect = ex.SystemError("BANANA") self.assertFalse(cinder.check_cinder_exists())
def _await_attach_volumes(instance, devices): timeout = 10 step = 2 while timeout > 0: if _count_attached_devices(instance, devices) == len(devices): return timeout -= step context.sleep(step) raise ex.SystemError( _("Error attach volume to instance %s") % instance.instance_name)
def _await_attach_volumes(instance, count_volumes): timeout = 10 step = 2 while timeout > 0: if len(_get_unmounted_devices(instance)) == count_volumes: return timeout -= step context.sleep(step) raise ex.SystemError("Error attach volume to instance %s" % instance.instance_name)
def tempdir(**kwargs): argdict = kwargs.copy() if 'dir' not in argdict: argdict['dir'] = '/tmp/' tmpdir = tempfile.mkdtemp(**argdict) try: yield tmpdir finally: try: shutil.rmtree(tmpdir) except OSError as e: raise ex.SystemError("Failed to delete temp dir %s (reason: %s)" % (tmpdir, e))
def _create_attach_volume(ctx, instance, size, display_name=None): volume = cinder.client().volumes.create(size=size, display_name=display_name) conductor.append_volume(ctx, instance, volume.id) while volume.status != 'available': volume = cinder.get_volume(volume.id) if volume.status == 'error': raise ex.SystemError(_("Volume %s has error status") % volume.id) context.sleep(1) resp = nova.client().volumes.create_server_volume(instance.instance_id, volume.id, None) return resp.device
def recv(self, size): try: return os.read(self.process.stdout.fileno(), size) except IOError as e: raise ex.SystemError(e)
def _await_available(volume): volume = cinder.get_volume(volume.id) if volume.status == 'error': raise ex.SystemError(_("Volume %s has error status") % volume.id) return volume.status == 'available'