def _get_server_admin_password(self, server): """Determine the admin password for a server on creation.""" if 'adminPass' in server: password = server['adminPass'] else: password = utils.generate_password() return password
def test_generate_password(self): password = utils.generate_password() self.assertTrue([c for c in password if c in '0123456789']) self.assertTrue([c for c in password if c in 'abcdefghijklmnopqrstuvwxyz']) self.assertTrue([c for c in password if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'])
def _get_server_admin_password(self, server): """Determine the admin password for a server on creation.""" try: password = server['adminPass'] except KeyError: password = utils.generate_password() return password
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = self._get_instance(context, id, want_objects=True) try: self.compute_api.rescue(context, instance, rescue_password=password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'rescue') except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) except NotImplementedError: msg = _("The rescue operation is not implemented by this " "cloud.") raise exc.HTTPNotImplemented(explanation=msg) return {'adminPass': password}
def add_console(self, context, instance_id, password=None, port=None, **kwargs): instance = self.db.instance_get(context, instance_id) host = instance['host'] name = instance['name'] pool = self.get_pool_for_instance_host(context, host) try: console = self.db.console_get_by_pool_instance( context, pool['id'], instance['uuid']) except exception.NotFound: LOG.debug(_('Adding console'), instance=instance) if not password: password = utils.generate_password(8) if not port: port = self.driver.get_port(context) console_data = { 'instance_name': name, 'instance_uuid': instance['uuid'], 'password': password, 'pool_id': pool['id'] } if port: console_data['port'] = port console = self.db.console_create(context, console_data) self.driver.setup_console(context, console) return console['id']
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = common.get_instance(self.compute_api, context, id, want_objects=True) rescue_image_ref = None if body['rescue'] and 'rescue_image_ref' in body['rescue']: rescue_image_ref = body['rescue']['rescue_image_ref'] try: self.compute_api.rescue(context, instance, rescue_password=password, rescue_image_ref=rescue_image_ref) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'rescue') except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) if CONF.enable_instance_password: return {'adminPass': password} else: return {}
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = self._get_instance(context, id, want_objects=True) try: rescue_image_ref = None if self.ext_mgr.is_loaded("os-extended-rescue-with-image"): if body['rescue'] and 'rescue_image_ref' in body['rescue']: rescue_image_ref = body['rescue']['rescue_image_ref'] self.compute_api.rescue(context, instance, rescue_password=password, rescue_image_ref=rescue_image_ref) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'rescue') except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) except NotImplementedError: msg = _("The rescue operation is not implemented by this " "cloud.") raise exc.HTTPNotImplemented(explanation=msg) return {'adminPass': password}
def create(self, req): """ Creates a new server for a given user """ env = self._deserialize_create(req) if not env: return faults.Fault(exc.HTTPUnprocessableEntity()) context = req.environ['nova.context'] key_name = None key_data = None key_pairs = auth_manager.AuthManager.get_key_pairs(context) if key_pairs: key_pair = key_pairs[0] key_name = key_pair['name'] key_data = key_pair['public_key'] image_id = common.get_image_id_from_image_hash(self._image_service, context, env['server']['imageId']) kernel_id, ramdisk_id = self._get_kernel_ramdisk_from_image( req, image_id) # Metadata is a list, not a Dictionary, because we allow duplicate keys # (even though JSON can't encode this) # In future, we may not allow duplicate keys. # However, the CloudServers API is not definitive on this front, # and we want to be compatible. metadata = [] if env['server'].get('metadata'): for k, v in env['server']['metadata'].items(): metadata.append({'key': k, 'value': v}) personality = env['server'].get('personality') injected_files = [] if personality: injected_files = self._get_injected_files(personality) try: instances = self.compute_api.create( context, instance_types.get_by_flavor_id(env['server']['flavorId']), image_id, kernel_id=kernel_id, ramdisk_id=ramdisk_id, display_name=env['server']['name'], display_description=env['server']['name'], key_name=key_name, key_data=key_data, metadata=metadata, injected_files=injected_files) except QuotaError as error: self._handle_quota_errors(error) builder = servers_views.get_view_builder(req) server = builder.build(instances[0], is_detail=False) password = "******" % (server['server']['name'][:4], utils.generate_password(12)) server['server']['adminPass'] = password self.compute_api.set_admin_password(context, server['server']['id'], password) return server
def add_console(self, context, instance_id, password=None, port=None, **kwargs): instance = self.db.instance_get(context, instance_id) host = instance['host'] name = instance['name'] pool = self.get_pool_for_instance_host(context, host) try: console = self.db.console_get_by_pool_instance(context, pool['id'], instance_id) except exception.NotFound: logging.debug(_('Adding console')) if not password: password = utils.generate_password(8) if not port: port = self.driver.get_port(context) console_data = {'instance_name': name, 'instance_id': instance_id, 'password': password, 'pool_id': pool['id']} if port: console_data['port'] = port console = self.db.console_create(context, console_data) self.driver.setup_console(context, console) return console['id']
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = common.get_instance(self.compute_api, context, id, want_objects=True) rescue_image_ref = None if body['rescue'] and 'rescue_image_ref' in body['rescue']: rescue_image_ref = body['rescue']['rescue_image_ref'] try: self.compute_api.rescue(context, instance, rescue_password=password, rescue_image_ref=rescue_image_ref) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'rescue', id) except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) if CONF.enable_instance_password: return {'adminPass': password} else: return {}
def test_generate_password(self): password = utils.generate_password() self.assertTrue([c for c in password if c in '0123456789']) self.assertTrue( [c for c in password if c in 'abcdefghijklmnopqrstuvwxyz']) self.assertTrue( [c for c in password if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'])
def _get_password_v214(self, req, evacuate_body): if 'adminPass' in evacuate_body: password = evacuate_body['adminPass'] else: password = utils.generate_password() return password
def create(self, req): """ Creates a new server for a given user """ env = self._deserialize_create(req) if not env: return faults.Fault(exc.HTTPUnprocessableEntity()) context = req.environ['nova.context'] key_name = None key_data = None key_pairs = auth_manager.AuthManager.get_key_pairs(context) if key_pairs: key_pair = key_pairs[0] key_name = key_pair['name'] key_data = key_pair['public_key'] image_id = common.get_image_id_from_image_hash( self._image_service, context, env['server']['imageId']) kernel_id, ramdisk_id = self._get_kernel_ramdisk_from_image( req, image_id) # Metadata is a list, not a Dictionary, because we allow duplicate keys # (even though JSON can't encode this) # In future, we may not allow duplicate keys. # However, the CloudServers API is not definitive on this front, # and we want to be compatible. metadata = [] if env['server'].get('metadata'): for k, v in env['server']['metadata'].items(): metadata.append({'key': k, 'value': v}) personality = env['server'].get('personality') injected_files = [] if personality: injected_files = self._get_injected_files(personality) try: instances = self.compute_api.create( context, instance_types.get_by_flavor_id(env['server']['flavorId']), image_id, kernel_id=kernel_id, ramdisk_id=ramdisk_id, display_name=env['server']['name'], display_description=env['server']['name'], key_name=key_name, key_data=key_data, metadata=metadata, injected_files=injected_files) except QuotaError as error: self._handle_quota_errors(error) builder = servers_views.get_view_builder(req) server = builder.build(instances[0], is_detail=False) password = "******" % (server['server']['name'][:4], utils.generate_password(12)) server['server']['adminPass'] = password self.compute_api.set_admin_password(context, server['server']['id'], password) return server
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'admin_password' in body['rescue']: password = body['rescue']['admin_password'] else: password = utils.generate_password() instance = common.get_instance(self.compute_api, context, id, want_objects=True) try: self.compute_api.rescue(context, instance, rescue_password=password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'rescue') except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) except NotImplementedError: msg = _("The rescue operation is not implemented by this cloud.") raise exc.HTTPNotImplemented(explanation=msg) if CONF.enable_instance_password: return {'admin_password': password} else: return {}
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = self._get_instance(context, id) try: self.compute_api.rescue(context, instance, rescue_password=password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'rescue') except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) return {'adminPass': password}
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = common.get_instance(self.compute_api, context, id) try: rescue_image_ref = None if self.ext_mgr.is_loaded("os-extended-rescue-with-image"): if body['rescue'] and 'rescue_image_ref' in body['rescue']: rescue_image_ref = self._rescue_image_validation( body['rescue']['rescue_image_ref']) self.compute_api.rescue(context, instance, rescue_password=password, rescue_image_ref=rescue_image_ref) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'rescue', id) except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) return {'adminPass': password}
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = common.get_instance(self.compute_api, context, id) try: rescue_image_ref = None if self.ext_mgr.is_loaded("os-extended-rescue-with-image"): if body['rescue'] and 'rescue_image_ref' in body['rescue']: rescue_image_ref = self._rescue_image_validation( body['rescue']['rescue_image_ref']) self.compute_api.rescue(context, instance, rescue_password=password, rescue_image_ref=rescue_image_ref) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'rescue', id) except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) return {'adminPass': password}
def test_user_create(self): secret = utils.generate_password() body = dict(user=dict(name='test_guy', access='acc3', secret=secret, admin=True)) req = webob.Request.blank('/v1.0/users') req.headers["Content-Type"] = "application/json" req.method = 'POST' req.body = json.dumps(body) res = req.get_response(fakes.wsgi_app()) res_dict = json.loads(res.body) self.assertEqual(res.status_int, 200) # NOTE(justinsb): This is a questionable assertion in general # fake sets id=name, but others might not... self.assertEqual(res_dict['user']['id'], 'test_guy') self.assertEqual(res_dict['user']['name'], 'test_guy') self.assertEqual(res_dict['user']['access'], 'acc3') self.assertEqual(res_dict['user']['secret'], secret) self.assertEqual(res_dict['user']['admin'], True) self.assertTrue('test_guy' in [u.id for u in fakes.FakeAuthManager.auth_data]) self.assertEqual(len(fakes.FakeAuthManager.auth_data), 3)
def _get_server_admin_password(self, server): """ Determine the admin password for a server on creation """ password = server.get('adminPass') if password is None: return utils.generate_password(16) if not isinstance(password, basestring) or password == '': msg = _("Invalid adminPass") raise exc.HTTPBadRequest(msg) return password
def _rescue(self, input_dict, req, instance_id): """Rescue an instance.""" context = req.environ["nova.context"] if input_dict['rescue'] and 'adminPass' in input_dict['rescue']: password = input_dict['rescue']['adminPass'] else: password = utils.generate_password(FLAGS.password_length) self.compute_api.rescue(context, instance_id, rescue_password=password) return {'adminPass': password}
def _get_server_admin_password(self, server): """ Determine the admin password for a server on creation """ password = server.get("adminPass") if password is None: return utils.generate_password(FLAGS.password_length) if not isinstance(password, basestring) or password == "": msg = _("Invalid adminPass") raise exc.HTTPBadRequest(explanation=msg) return password
def _evacuate(self, req, id, body): """Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] authorize(context) if not self.is_valid_body(body, "evacuate"): raise exc.HTTPBadRequest(_("Malformed request body")) evacuate_body = body["evacuate"] try: host = evacuate_body["host"] on_shared_storage = strutils.bool_from_string( evacuate_body["onSharedStorage"]) except (TypeError, KeyError): msg = _("host and onSharedStorage must be specified.") raise exc.HTTPBadRequest(explanation=msg) password = None if 'adminPass' in evacuate_body: # check that if requested to evacuate server on shared storage # password not specified if on_shared_storage: msg = _("admin password can't be changed on existing disk") raise exc.HTTPBadRequest(explanation=msg) password = evacuate_body['adminPass'] elif not on_shared_storage: password = utils.generate_password() try: self.host_api.service_get_by_compute_host(context, host) except exception.NotFound: msg = _("Compute host %s not found.") % host raise exc.HTTPNotFound(explanation=msg) try: instance = self.compute_api.get(context, id) if instance['host'] == host: msg = _("The target host can't be the same one.") raise exc.HTTPBadRequest(explanation=msg) self.compute_api.evacuate(context, instance, host, on_shared_storage, password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'evacuate') except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.ComputeServiceInUse as e: raise exc.HTTPBadRequest(explanation=e.format_message()) if password: return {'adminPass': password}
def _evacuate(self, req, id, body): """Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] authorize(context) if not self.is_valid_body(body, "evacuate"): raise exc.HTTPBadRequest(_("Malformed request body")) evacuate_body = body["evacuate"] try: host = evacuate_body["host"] on_shared_storage = strutils.bool_from_string( evacuate_body["onSharedStorage"]) except (TypeError, KeyError): msg = _("host and onSharedStorage must be specified.") raise exc.HTTPBadRequest(explanation=msg) password = None if 'adminPass' in evacuate_body: # check that if requested to evacuate server on shared storage # password not specified if on_shared_storage: msg = _("admin password can't be changed on existing disk") raise exc.HTTPBadRequest(explanation=msg) password = evacuate_body['adminPass'] elif not on_shared_storage: password = utils.generate_password() try: self.host_api.service_get_by_compute_host(context, host) except exception.NotFound: msg = _("Compute host %s not found.") % host raise exc.HTTPNotFound(explanation=msg) try: instance = self.compute_api.get(context, id, want_objects=True) if instance.host == host: msg = _("The target host can't be the same one.") raise exc.HTTPBadRequest(explanation=msg) self.compute_api.evacuate(context, instance, host, on_shared_storage, password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'evacuate') except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.ComputeServiceInUse as e: raise exc.HTTPBadRequest(explanation=e.format_message()) if password: return {'adminPass': password}
def _get_server_admin_password(self, server): """Determine the admin password for a server on creation.""" try: password = server['admin_password'] self._validate_admin_password(password) except KeyError: password = utils.generate_password() except ValueError: raise exc.HTTPBadRequest(explanation=_("Invalid admin_password")) return password
def _get_server_admin_password(self, server): """Determine the admin password for a server on creation.""" try: password = server['adminPass'] self._validate_admin_password(password) except KeyError: password = utils.generate_password() except ValueError: raise exc.HTTPBadRequest(explanation=_("Invalid adminPass")) return password
def test_user_update(self): new_secret = utils.generate_password() body = dict(user=dict(name='guy2', access='acc2', secret=new_secret)) req = fakes.HTTPRequest.blank('/v2/fake/users/id2') res_dict = self.controller.update(req, 'id2', body) self.assertEqual(res_dict['user']['id'], 'id2') self.assertEqual(res_dict['user']['name'], 'guy2') self.assertEqual(res_dict['user']['access'], 'acc2') self.assertEqual(res_dict['user']['secret'], new_secret) self.assertEqual(res_dict['user']['admin'], True)
def _rescue(self, input_dict, req, instance_id): """Rescue an instance.""" context = req.environ["nova.context"] if input_dict["rescue"] and "adminPass" in input_dict["rescue"]: password = input_dict["rescue"]["adminPass"] else: password = utils.generate_password(FLAGS.password_length) instance = self._get_instance(context, instance_id) self.compute_api.rescue(context, instance, rescue_password=password) return {"adminPass": password}
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password(FLAGS.password_length) instance = self._get_instance(context, id) self.compute_api.rescue(context, instance, rescue_password=password) return {'adminPass': password}
def test_user_update(self): new_secret = utils.generate_password() body = dict(user=dict(name="guy2", access="acc2", secret=new_secret)) req = fakes.HTTPRequest.blank("/v2/fake/users/id2") res_dict = self.controller.update(req, "id2", body) self.assertEqual(res_dict["user"]["id"], "id2") self.assertEqual(res_dict["user"]["name"], "guy2") self.assertEqual(res_dict["user"]["access"], "acc2") self.assertEqual(res_dict["user"]["secret"], new_secret) self.assertEqual(res_dict["user"]["admin"], True)
def _evacuate(self, req, id, body): """Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] authorize(context) evacuate_body = body["evacuate"] host = evacuate_body.get("host") on_shared_storage = strutils.bool_from_string( evacuate_body["onSharedStorage"]) password = None if 'adminPass' in evacuate_body: # check that if requested to evacuate server on shared storage # password not specified if on_shared_storage: msg = _("admin password can't be changed on existing disk") raise exc.HTTPBadRequest(explanation=msg) password = evacuate_body['adminPass'] elif not on_shared_storage: password = utils.generate_password() if host is not None: try: self.host_api.service_get_by_compute_host(context, host) except exception.ComputeHostNotFound: msg = _("Compute host %s not found.") % host raise exc.HTTPNotFound(explanation=msg) instance = common.get_instance(self.compute_api, context, id) if instance.host == host: msg = _("The target host can't be the same one.") raise exc.HTTPBadRequest(explanation=msg) try: self.compute_api.evacuate(context, instance, host, on_shared_storage, password) except exception.InstanceUnknownCell as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'evacuate', id) except exception.ComputeServiceInUse as e: raise exc.HTTPBadRequest(explanation=e.format_message()) if CONF.enable_instance_password: return {'adminPass': password} else: return {}
def _evacuate(self, req, id, body): """Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] authorize(context) evacuate_body = body["evacuate"] host = evacuate_body.get("host") on_shared_storage = strutils.bool_from_string( evacuate_body["onSharedStorage"]) password = None if 'adminPass' in evacuate_body: # check that if requested to evacuate server on shared storage # password not specified if on_shared_storage: msg = _("admin password can't be changed on existing disk") raise exc.HTTPBadRequest(explanation=msg) password = evacuate_body['adminPass'] elif not on_shared_storage: password = utils.generate_password() if host is not None: try: self.host_api.service_get_by_compute_host(context, host) except exception.ComputeHostNotFound: msg = _("Compute host %s not found.") % host raise exc.HTTPNotFound(explanation=msg) instance = common.get_instance(self.compute_api, context, id) if instance.host == host: msg = _("The target host can't be the same one.") raise exc.HTTPBadRequest(explanation=msg) try: self.compute_api.evacuate(context, instance, host, on_shared_storage, password) except exception.InstanceUnknownCell as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'evacuate', id) except exception.ComputeServiceInUse as e: raise exc.HTTPBadRequest(explanation=e.format_message()) if CONF.enable_instance_password: return {'adminPass': password} else: return {}
def _get_password(self, req, evacuate_body, on_shared_storage): password = None if 'adminPass' in evacuate_body: # check that if requested to evacuate server on shared storage # password not specified if on_shared_storage: msg = _("admin password can't be changed on existing disk") raise exc.HTTPBadRequest(explanation=msg) password = evacuate_body['adminPass'] elif not on_shared_storage: password = utils.generate_password() return password
def _evacuate(self, req, id, body): """ Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] if not context.is_admin: msg = _("Instance evacuate is admin only functionality") raise exc.HTTPForbidden(explanation=msg) authorize(context) try: if len(body) != 1: raise exc.HTTPBadRequest(_("Malformed request body")) evacuate_body = body["evacuate"] host = evacuate_body["host"] on_shared_storage = utils.bool_from_str( evacuate_body["onSharedStorage"]) password = None if 'adminPass' in evacuate_body: # check that if requested to evacuate server on shared storage # password not specified if on_shared_storage: msg = _("admin password can't be changed on existing disk") raise exc.HTTPBadRequest(explanation=msg) password = evacuate_body['adminPass'] elif not on_shared_storage: password = utils.generate_password() except (TypeError, KeyError): msg = _("host and onSharedStorage must be specified.") raise exc.HTTPBadRequest(explanation=msg) try: instance = self.compute_api.get(context, id) self.compute_api.evacuate(context, instance, host, on_shared_storage, password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'evacuate') except Exception as e: msg = _("Error in evacuate, %s") % e LOG.exception(msg, instance=instance) raise exc.HTTPBadRequest(explanation=msg) if password: return {'adminPass': password}
def _evacuate(self, req, id, body): """ Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] if not context.is_admin: msg = _("Instance evacuate is admin only functionality") raise exc.HTTPForbidden(explanation=msg) authorize(context) try: if len(body) != 1: raise exc.HTTPBadRequest(_("Malformed request body")) evacuate_body = body["evacuate"] host = evacuate_body["host"] on_shared_storage = utils.bool_from_str( evacuate_body["onSharedStorage"]) password = None if 'adminPass' in evacuate_body: # check that if requested to evacuate server on shared storage # password not specified if on_shared_storage: msg = _("admin password can't be changed on existing disk") raise exc.HTTPBadRequest(explanation=msg) password = evacuate_body['adminPass'] elif not on_shared_storage: password = utils.generate_password() except (TypeError, KeyError): msg = _("host and onSharedStorage must be specified.") raise exc.HTTPBadRequest(explanation=msg) try: instance = self.compute_api.get(context, id) self.compute_api.evacuate(context, instance, host, on_shared_storage, password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'evacuate') except Exception as e: msg = _("Error in evacuate, %s") % e LOG.exception(msg, instance=instance) raise exc.HTTPBadRequest(explanation=msg) if password: return {'adminPass': password}
def rescue(self, req, id, body={}): """Permit users to rescue the server.""" context = req.environ["nova.context"] try: if "rescue" in body and body["rescue"] and "adminPass" in body["rescue"]: password = body["rescue"]["adminPass"] else: password = utils.generate_password(FLAGS.password_length) self.compute_api.rescue(context, id, rescue_password=password) except Exception: readable = traceback.format_exc() LOG.exception(_("compute.api::rescue %s"), readable) raise exc.HTTPUnprocessableEntity() return {"adminPass": password}
def test_user_create(self): secret = utils.generate_password() body = dict(user=dict(name="test_guy", access="acc3", secret=secret, admin=True)) req = fakes.HTTPRequest.blank("/v2/fake/users") res_dict = self.controller.create(req, body) # NOTE(justinsb): This is a questionable assertion in general # fake sets id=name, but others might not... self.assertEqual(res_dict["user"]["id"], "test_guy") self.assertEqual(res_dict["user"]["name"], "test_guy") self.assertEqual(res_dict["user"]["access"], "acc3") self.assertEqual(res_dict["user"]["secret"], secret) self.assertEqual(res_dict["user"]["admin"], True) self.assertTrue("test_guy" in [u.id for u in fakes.FakeAuthManager.auth_data]) self.assertEqual(len(fakes.FakeAuthManager.auth_data), 3)
def rescue(self, req, id, body={}): """Permit users to rescue the server.""" context = req.environ["nova.context"] try: if 'rescue' in body and body['rescue'] and \ 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password(FLAGS.password_length) self.compute_api.rescue(context, id, rescue_password=password) except Exception: readable = traceback.format_exc() LOG.exception(_("compute.api::rescue %s"), readable) raise exc.HTTPUnprocessableEntity() return {'adminPass': password}
def _action_rebuild(self, info, request, instance_id): context = request.environ['nova.context'] instance = self._get_server(context, instance_id) try: image_href = info["rebuild"]["imageRef"] except (KeyError, TypeError): msg = _("Could not parse imageRef from request.") LOG.debug(msg) raise exc.HTTPBadRequest(explanation=msg) personality = info["rebuild"].get("personality", []) injected_files = [] if personality: injected_files = self._get_injected_files(personality) metadata = info["rebuild"].get("metadata") name = info["rebuild"].get("name") if metadata: self._validate_metadata(metadata) if 'rebuild' in info and 'adminPass' in info['rebuild']: password = info['rebuild']['adminPass'] else: password = utils.generate_password(FLAGS.password_length) try: self.compute_api.rebuild(context, instance, image_href, password, name=name, metadata=metadata, files_to_inject=injected_files) except exception.RebuildRequiresActiveInstance: msg = _("Instance %s must be active to rebuild.") % instance_id raise exc.HTTPConflict(explanation=msg) except exception.InstanceNotFound: msg = _("Instance %s could not be found") % instance_id raise exc.HTTPNotFound(explanation=msg) instance = self._get_server(context, instance_id) view = self._view_builder.show(request, instance) view['server']['adminPass'] = password return view
def _evacuate(self, req, id, body): """ Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] authorize(context) try: if len(body) != 1: raise exc.HTTPBadRequest(_("Malformed request body")) evacuate_body = body["evacuate"] host = evacuate_body["host"] on_shared_storage = strutils.bool_from_string( evacuate_body["on_shared_storage"]) password = None if 'admin_password' in evacuate_body: # check that if requested to evacuate server on shared storage # password not specified if on_shared_storage: msg = _("admin password can't be changed on existing disk") raise exc.HTTPBadRequest(explanation=msg) password = evacuate_body['admin_password'] elif not on_shared_storage: password = utils.generate_password() except (TypeError, KeyError): msg = _("host and on_shared_storage must be specified.") raise exc.HTTPBadRequest(explanation=msg) try: instance = self.compute_api.get(context, id) self.compute_api.evacuate(context, instance, host, on_shared_storage, password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'evacuate') except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.ComputeServiceUnavailable as e: raise exc.HTTPBadRequest(explanation=e.format_message()) return {'admin_password': password}
def rebuild_vm(uid, image_href, context): """ Rebuilds the specified VM with the supplied OsTemplate mixin. uid -- id of the instance image_href -- image reference. context -- the os context """ instance = get_vm(uid, context) admin_password = utils.generate_password() kwargs = {} try: COMPUTE_API.rebuild(context, instance, image_href, admin_password, **kwargs) except Exception as e: raise AttributeError(e.message)
def _evacuate(self, req, id, body): """ Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] authorize(context) try: if len(body) != 1: raise exc.HTTPBadRequest(_("Malformed request body")) evacuate_body = body["evacuate"] host = evacuate_body["host"] on_shared_storage = strutils.bool_from_string( evacuate_body["on_shared_storage"]) password = None if 'admin_password' in evacuate_body: # check that if requested to evacuate server on shared storage # password not specified if on_shared_storage: msg = _("admin password can't be changed on existing disk") raise exc.HTTPBadRequest(explanation=msg) password = evacuate_body['admin_password'] elif not on_shared_storage: password = utils.generate_password() except (TypeError, KeyError): msg = _("host and on_shared_storage must be specified.") raise exc.HTTPBadRequest(explanation=msg) try: instance = self.compute_api.get(context, id) self.compute_api.evacuate(context, instance, host, on_shared_storage, password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'evacuate') except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.ComputeServiceUnavailable as e: raise exc.HTTPBadRequest(explanation=e.format_message()) return {'admin_password': password}
def test_user_update(self): new_secret = utils.generate_password() body = dict(user=dict(name='guy2', access='acc2', secret=new_secret)) req = webob.Request.blank('/v1.0/users/id2') req.headers["Content-Type"] = "application/json" req.method = 'PUT' req.body = json.dumps(body) res = req.get_response(fakes.wsgi_app()) res_dict = json.loads(res.body) self.assertEqual(res.status_int, 200) self.assertEqual(res_dict['user']['id'], 'id2') self.assertEqual(res_dict['user']['name'], 'guy2') self.assertEqual(res_dict['user']['access'], 'acc2') self.assertEqual(res_dict['user']['secret'], new_secret) self.assertEqual(res_dict['user']['admin'], True)
def set_admin_password(self, context, instance_id, new_pass=None): """Set the root/admin password for an instance on this server.""" context = context.elevated() instance_ref = self.db.instance_get(context, instance_id) instance_id = instance_ref['id'] instance_state = instance_ref['state'] expected_state = power_state.RUNNING if instance_state != expected_state: LOG.warn(_('trying to reset the password on a non-running ' 'instance: %(instance_id)s (state: %(instance_state)s ' 'expected: %(expected_state)s)') % locals()) LOG.audit(_('instance %s: setting admin password'), instance_ref['name']) if new_pass is None: # Generate a random password new_pass = utils.generate_password(FLAGS.password_length) self.driver.set_admin_password(instance_ref, new_pass) self._update_state(context, instance_id)
def test_user_create(self): secret = utils.generate_password() body = dict(user=dict( name='test_guy', access='acc3', secret=secret, admin=True)) req = fakes.HTTPRequest.blank('/v2/fake/users') res_dict = self.controller.create(req, body) # NOTE(justinsb): This is a questionable assertion in general # fake sets id=name, but others might not... self.assertEqual(res_dict['user']['id'], 'test_guy') self.assertEqual(res_dict['user']['name'], 'test_guy') self.assertEqual(res_dict['user']['access'], 'acc3') self.assertEqual(res_dict['user']['secret'], secret) self.assertEqual(res_dict['user']['admin'], True) self.assertTrue( 'test_guy' in [u.id for u in fakes.FakeAuthManager.auth_data]) self.assertEqual(len(fakes.FakeAuthManager.auth_data), 3)
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password(CONF.password_length) instance = self._get_instance(context, id) try: self.compute_api.rescue(context, instance, rescue_password=password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'rescue') return {'adminPass': password}
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = self._get_instance(context, id) try: self.compute_api.rescue(context, instance, rescue_password=password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'rescue') return {'adminPass': password}
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = common.get_instance(self.compute_api, context, id) context.can(rescue_policies.BASE_POLICY_NAME, target={ 'user_id': instance.user_id, 'project_id': instance.project_id }) rescue_image_ref = None if body['rescue']: rescue_image_ref = body['rescue'].get('rescue_image_ref') allow_bfv_rescue = api_version_request.is_supported(req, '2.87') try: self.compute_api.rescue(context, instance, rescue_password=password, rescue_image_ref=rescue_image_ref, allow_bfv_rescue=allow_bfv_rescue) except ( exception.InstanceIsLocked, exception.OperationNotSupportedForVTPM, exception.InvalidVolume, ) as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as e: common.raise_http_conflict_for_instance_invalid_state( e, 'rescue', id) except ( exception.InstanceNotRescuable, exception.UnsupportedRescueImage, ) as e: raise exc.HTTPBadRequest(explanation=e.format_message()) if CONF.api.enable_instance_password: return {'adminPass': password} else: return {}
def _action_rebuild(self, info, request, instance_id): context = request.environ['nova.context'] instance = self._get_server(context, instance_id) try: image_href = info["rebuild"]["imageRef"] except (KeyError, TypeError): msg = _("Could not parse imageRef from request.") LOG.debug(msg) raise exc.HTTPBadRequest(explanation=msg) personality = info["rebuild"].get("personality", []) injected_files = [] if personality: injected_files = self._get_injected_files(personality) metadata = info["rebuild"].get("metadata") name = info["rebuild"].get("name") if metadata: self._validate_metadata(metadata) if 'rebuild' in info and 'adminPass' in info['rebuild']: password = info['rebuild']['adminPass'] else: password = utils.generate_password(FLAGS.password_length) try: self.compute_api.rebuild(context, instance, image_href, password, name=name, metadata=metadata, files_to_inject=injected_files) except exception.RebuildRequiresActiveInstance: msg = _("Instance %s must be active to rebuild.") % instance_id raise exc.HTTPConflict(explanation=msg) except exception.InstanceNotFound: msg = _("Instance %s could not be found") % instance_id raise exc.HTTPNotFound(explanation=msg) instance = self._get_server(context, instance_id) self._add_instance_faults(context, [instance]) view = self._view_builder.show(request, instance) view['server']['adminPass'] = password return view
def _action_rebuild(self, info, request, instance_id): context = request.environ['nova.context'] try: image_id = info["rebuild"]["imageId"] except (KeyError, TypeError): msg = _("Could not parse imageId from request.") LOG.debug(msg) raise exc.HTTPBadRequest(explanation=msg) password = utils.generate_password(FLAGS.password_length) try: self.compute_api.rebuild(context, instance_id, image_id, password) except exception.RebuildRequiresActiveInstance: msg = _("Instance %s must be active to rebuild.") % instance_id raise exc.HTTPConflict(explanation=msg) return webob.Response(status_int=202)
def rebuild_vm(uid, image_href, context): """ Rebuilds the specified VM with the supplied OsTemplate mixin. uid -- id of the instance image_href -- image reference. context -- the os context """ instance = get_vm(uid, context) admin_password = utils.generate_password(FLAGS.password_length) kwargs = {} try: COMPUTE_API.rebuild(context, instance, image_href, admin_password, **kwargs) except exception.InstanceInvalidState: raise AttributeError('VM is in an invalid state.') except exception.ImageNotFound: raise AttributeError('Cannot find image for rebuild')