Exemplo n.º 1
0
 def instance_root_create(self, req, body, instance_id,
                          cluster_instances=None):
     LOG.info(_LI("Enabling root for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     user_name = context.user
     password = ClusterRootController._get_password_from_body(body)
     root = models.ClusterRoot.create(context, instance_id, user_name,
                                      password, cluster_instances)
     return wsgi.Result(views.RootCreatedView(root).data(), 200)
Exemplo n.º 2
0
 def root_index(self, req, tenant_id, instance_id, is_cluster):
     """Returns True if root is enabled; False otherwise."""
     if is_cluster:
         raise exception.ClusterOperationNotSupported(
             operation='show_root')
     LOG.info(_LI("Getting root enabled for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     is_root_enabled = models.Root.load(context, instance_id)
     return wsgi.Result(views.RootEnabledView(is_root_enabled).data(), 200)
Exemplo n.º 3
0
 def instance_root_index(self, req, tenant_id, instance_id):
     LOG.info(_LI("Getting root enabled for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     try:
         is_root_enabled = models.ClusterRoot.load(context, instance_id)
     except exception.UnprocessableEntity:
         raise exception.UnprocessableEntity(
             "Cluster %s is not ready." % instance_id)
     return wsgi.Result(views.RootEnabledView(is_root_enabled).data(), 200)
Exemplo n.º 4
0
 def root_create(self, req, body, tenant_id, instance_id, is_cluster):
     if is_cluster:
         raise exception.ClusterOperationNotSupported(
             operation='enable_root')
     LOG.info(_LI("Enabling root for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     user_name = context.user
     password = DefaultRootController._get_password_from_body(body)
     root = models.Root.create(context, instance_id,
                               user_name, password)
     return wsgi.Result(views.RootCreatedView(root).data(), 200)
Exemplo n.º 5
0
 def root_delete(self, req, tenant_id, instance_id, is_cluster):
     if is_cluster:
         raise exception.ClusterOperationNotSupported(
             operation='disable_root')
     LOG.info(_LI("Disabling root for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     is_root_enabled = common_utils.Root.load(context, instance_id)
     if not is_root_enabled:
         raise exception.UserNotFound(uuid="root")
     common_utils.Root.delete(context, instance_id)
     return wsgi.Result(None, 200)
Exemplo n.º 6
0
 def instance_root_create(self, req, body, instance_id,
                          cluster_instances=None):
     LOG.info(_LI("Enabling root for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     user_name = context.user
     if body:
         password = body['password'] if 'password' in body else None
     else:
         password = None
     root = models.VerticaRoot.create(context, instance_id, user_name,
                                      password, cluster_instances)
     return wsgi.Result(views.RootCreatedView(root).data(), 200)
Exemplo n.º 7
0
 def root_create(self, req, body, tenant_id, instance_id, is_cluster):
     if is_cluster:
         raise exception.ClusterOperationNotSupported(
             operation='enable_root')
     LOG.info(_LI("Enabling root for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     user_name = context.user
     if body:
         password = body['password'] if 'password' in body else None
     else:
         password = None
     root = models.Root.create(context, instance_id,
                               user_name, password)
     return wsgi.Result(views.RootCreatedView(root).data(), 200)
Exemplo n.º 8
0
 def root_delete(self, req, tenant_id, instance_id, is_cluster):
     if is_cluster:
         raise exception.ClusterOperationNotSupported(
             operation='disable_root')
     LOG.info(_LI("Disabling root for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     try:
         found_user = self._find_root_user(context, instance_id)
     except (ValueError, AttributeError) as e:
         raise exception.BadRequest(msg=str(e))
     if not found_user:
         raise exception.UserNotFound(uuid="root")
     models.Root.delete(context, instance_id)
     return wsgi.Result(None, 200)
Exemplo n.º 9
0
 def action(self, req, body, tenant_id, id):
     """
     Handles requests that modify existing instances in some manner. Actions
     could include 'resize', 'restart', 'reset_password'
     :param req: http request object
     :param body: deserialized body of the request as a dict
     :param tenant_id: the tenant id for whom owns the instance
     :param id: instance id
     """
     LOG.debug("instance action req : '%s'\n\n", req)
     if not body:
         raise exception.BadRequest(_("Invalid request body."))
     context = req.environ[wsgi.CONTEXT_KEY]
     instance = models.Instance.load(context, id)
     _actions = {
         'restart': self._action_restart,
         'resize': self._action_resize,
         'reset_password': self._action_reset_password,
         'promote_to_replica_source':
         self._action_promote_to_replica_source,
         'eject_replica_source': self._action_eject_replica_source,
     }
     selected_action = None
     action_name = None
     for key in body:
         if key in _actions:
             selected_action = _actions[key]
             action_name = key
     LOG.info(_LI("Performing %(action_name)s action against "
                  "instance %(instance_id)s for tenant '%(tenant_id)s'"),
              {'action_name': action_name, 'instance_id': id,
               'tenant_id': tenant_id})
     return selected_action(instance, body)
Exemplo n.º 10
0
    def update_all(self, req, body, tenant_id, instance_id):
        """Change the password of one or more users."""
        LOG.info(_LI("Updating user password for instance '%(id)s'\n"
                     "req : '%(req)s'\n\n") %
                 {"id": instance_id, "req": strutils.mask_password(req)})
        context = req.environ[wsgi.CONTEXT_KEY]
        self.authorize_target_action(context, 'user:update_all', instance_id)

        context.notification = notification.DBaaSUserChangePassword(
            context, request=req)
        users = body['users']
        usernames = [user['name'] for user in users]
        client = self.create_guest_client(context, instance_id)
        with StartNotification(context, instance_id=instance_id,
                               username="******".join(usernames)):

            try:
                user_models = self.parse_users_from_request(users)
                for model in user_models:
                    user_id = self.get_user_id(model)
                    if self.is_reserved_id(user_id):
                        raise exception.ReservedUserId(name=user_id)
                    if not self.find_user(client, user_id):
                        raise exception.UserNotFound(uuid=user_id)

                self.change_passwords(client, user_models)
            except (ValueError, AttributeError) as e:
                raise exception.BadRequest(str(e))

        return wsgi.Result(None, 202)
Exemplo n.º 11
0
    def update(self, req, body, tenant_id, instance_id, id):
        LOG.info(_LI("Updating user attributes for instance '%(id)s'\n"
                     "req : '%(req)s'\n\n") %
                 {"id": instance_id, "req": strutils.mask_password(req)})
        context = req.environ[wsgi.CONTEXT_KEY]
        self.authorize_target_action(context, 'user:update', instance_id)

        user_id = correct_id_with_req(id, req)

        updates = body['user']
        context.notification = notification.DBaaSUserUpdateAttributes(
            context, request=req)
        client = self.create_guest_client(context, instance_id)
        with StartNotification(context, instance_id=instance_id,
                               username=user_id):

            try:
                if self.is_reserved_id(user_id):
                    raise exception.ReservedUserId(name=user_id)

                model = self.find_user(client, user_id)
                if not model:
                    raise exception.UserNotFound(uuid=user_id)

                new_user_id = self.apply_user_updates(model, updates)
                if (new_user_id is not None and
                        self.find_user(client, new_user_id)):
                    raise exception.UserAlreadyExists(name=new_user_id)

                self.update_user(client, user_id, updates)
            except (ValueError, AttributeError) as e:
                raise exception.BadRequest(str(e))

        return wsgi.Result(None, 202)
Exemplo n.º 12
0
 def enable_root(self, root_password=None):
     """Resets the root password."""
     LOG.info(_LI("Enabling root."))
     user = models.DatastoreUser.root(password=root_password)
     if not self.is_root_enabled():
         self._create_user(user.name, user.password, 'pseudosuperuser')
     else:
         LOG.debug("Updating %s password." % user.name)
         try:
             out, err = system.exec_vsql_command(
                 self._get_database_password(),
                 system.ALTER_USER_PASSWORD % (user.name, user.password))
             if err:
                 if err.is_warning():
                     LOG.warning(err)
                 else:
                     LOG.error(err)
                     raise RuntimeError(
                         _("Failed to update %s "
                           "password.") % user.name)
         except exception.ProcessExecutionError:
             LOG.error(_("Failed to update %s password.") % user.name)
             raise RuntimeError(
                 _("Failed to update %s password.") % user.name)
     return user.serialize()
Exemplo n.º 13
0
 def action(self, req, body, tenant_id, id):
     """
     Handles requests that modify existing instances in some manner. Actions
     could include 'resize', 'restart', 'reset_password'
     :param req: http request object
     :param body: deserialized body of the request as a dict
     :param tenant_id: the tenant id for whom owns the instance
     :param id: ???
     """
     LOG.debug("instance action req : '%s'\n\n", req)
     if not body:
         raise exception.BadRequest(_("Invalid request body."))
     context = req.environ[wsgi.CONTEXT_KEY]
     instance = models.Instance.load(context, id)
     _actions = {
         'restart': self._action_restart,
         'resize': self._action_resize,
         'reset_password': self._action_reset_password,
         'promote_to_replica_source':
         self._action_promote_to_replica_source,
         'eject_replica_source': self._action_eject_replica_source,
     }
     selected_action = None
     action_name = None
     for key in body:
         if key in _actions:
             selected_action = _actions[key]
             action_name = key
     LOG.info(_LI("Performing %(action_name)s action against "
                  "instance %(instance_id)s for tenant '%(tenant_id)s'"),
              {'action_name': action_name, 'instance_id': id,
               'tenant_id': tenant_id})
     return selected_action(instance, body)
Exemplo n.º 14
0
    def update(self, req, id, body, tenant_id):
        """Updates the instance to attach/detach configuration."""
        LOG.info(
            _LI("Updating database instance '%(instance_id)s' for tenant "
                "'%(tenant_id)s'"), {
                    'instance_id': id,
                    'tenant_id': tenant_id
                })
        LOG.debug("req: %s", req)
        LOG.debug("body: %s", body)
        context = req.environ[wsgi.CONTEXT_KEY]

        instance = models.Instance.load(context, id)

        # If configuration is set, then we will update the instance to use the
        # new configuration. If configuration is empty, we want to disassociate
        # the instance from the configuration group and remove the active
        # overrides file.

        update_args = {}
        configuration_id = self._configuration_parse(context, body)
        if configuration_id:
            instance.assign_configuration(configuration_id)
        else:
            instance.unassign_configuration()

        update_args['configuration_id'] = configuration_id
        instance.update_db(**update_args)
        return wsgi.Result(None, 202)
Exemplo n.º 15
0
    def delete(self, req, tenant_id, instance_id, id):
        LOG.info(_LI("Delete instance '%(id)s'\n"
                     "req : '%(req)s'\n\n") %
                 {"id": instance_id, "req": req})
        context = req.environ[wsgi.CONTEXT_KEY]
        self.authorize_target_action(context, 'user:delete', instance_id)

        database_id = correct_id_with_req(id, req)
        context.notification = notification.DBaaSDatabaseDelete(context,
                                                                request=req)

        client = self.create_guest_client(context, instance_id)
        with StartNotification(context, instance_id=instance_id,
                               dbname=database_id):

            try:
                if self.is_reserved_id(database_id):
                    raise exception.ReservedDatabaseId(name=database_id)

                model = self.find_database(client, database_id)
                if not model:
                    raise exception.DatabaseNotFound(uuid=database_id)

                self.delete_database(client, model)
            except (ValueError, AttributeError) as e:
                raise exception.BadRequest(str(e))

        return wsgi.Result(None, 202)
Exemplo n.º 16
0
    def edit(self, req, id, body, tenant_id):
        """
        Updates the instance to set or unset one or more attributes.
        """
        LOG.info(_LI("Editing instance for tenant id %s."), tenant_id)
        LOG.debug("req: %s", strutils.mask_password(req))
        LOG.debug("body: %s", strutils.mask_password(body))
        context = req.environ[wsgi.CONTEXT_KEY]

        instance = models.Instance.load(context, id)

        args = {}
        args['detach_replica'] = ('replica_of' in body['instance'] or
                                  'slave_of' in body['instance'])

        if 'name' in body['instance']:
            args['name'] = body['instance']['name']
        if 'configuration' in body['instance']:
            args['configuration_id'] = self._configuration_parse(context, body)
        if 'datastore_version' in body['instance']:
            args['datastore_version'] = body['instance'].get(
                'datastore_version')

        self._modify_instance(context, req, instance, **args)
        return wsgi.Result(None, 202)
Exemplo n.º 17
0
 def enable_root(self, root_password=None):
     """Resets the root password."""
     LOG.info(_LI("Enabling root."))
     user = models.RootUser()
     user.name = "root"
     user.host = "%"
     user.password = root_password or utils.generate_random_password()
     if not self.is_root_enabled():
         self._create_user(user.name, user.password, 'pseudosuperuser')
     else:
         LOG.debug("Updating %s password." % user.name)
         try:
             out, err = system.exec_vsql_command(
                 self._get_database_password(),
                 system.ALTER_USER_PASSWORD % (user.name, user.password))
             if err:
                 if err.is_warning():
                     LOG.warning(err)
                 else:
                     LOG.error(err)
                     raise RuntimeError(_("Failed to update %s "
                                          "password.") % user.name)
         except exception.ProcessExecutionError:
             LOG.error(_("Failed to update %s password.") % user.name)
             raise RuntimeError(_("Failed to update %s password.")
                                % user.name)
     return user.serialize()
Exemplo n.º 18
0
    def edit(self, req, id, body, tenant_id):
        """
        Updates the instance to set or unset one or more attributes.
        """
        LOG.info(_LI("Editing instance for tenant id %s."), tenant_id)
        LOG.debug("req: %s", strutils.mask_password(req))
        LOG.debug("body: %s", strutils.mask_password(body))
        context = req.environ[wsgi.CONTEXT_KEY]

        instance = models.Instance.load(context, id)

        args = {}
        args['detach_replica'] = ('replica_of' in body['instance'] or
                                  'slave_of' in body['instance'])

        if 'name' in body['instance']:
            args['name'] = body['instance']['name']
        if 'configuration' in body['instance']:
            args['configuration_id'] = self._configuration_parse(context, body)
        if 'datastore_version' in body['instance']:
            args['datastore_version'] = body['instance'].get(
                'datastore_version')

        self._modify_instance(context, req, instance, **args)
        return wsgi.Result(None, 202)
Exemplo n.º 19
0
    def create(self, req, body, tenant_id):
        # TODO(hub-cap): turn this into middleware
        LOG.info(_LI("Creating a database instance for tenant '%s'"),
                 tenant_id)
        LOG.debug("req : '%s'\n\n", strutils.mask_password(req))
        LOG.debug("body : '%s'\n\n", strutils.mask_password(body))
        context = req.environ[wsgi.CONTEXT_KEY]
        context.notification = notification.DBaaSInstanceCreate(context,
                                                                request=req)
        datastore_args = body['instance'].get('datastore', {})
        datastore, datastore_version = (
            datastore_models.get_datastore_version(**datastore_args))
        image_id = datastore_version.image_id
        name = body['instance']['name']
        flavor_ref = body['instance']['flavorRef']
        flavor_id = utils.get_id_from_href(flavor_ref)

        configuration = self._configuration_parse(context, body)
        databases = populate_validated_databases(
            body['instance'].get('databases', []))
        database_names = [database.get('_name', '') for database in databases]
        users = None
        try:
            users = populate_users(body['instance'].get('users', []),
                                   database_names)
        except ValueError as ve:
            raise exception.BadRequest(msg=ve)

        if 'volume' in body['instance']:
            volume_info = body['instance']['volume']
            volume_size = int(volume_info['size'])
            volume_type = volume_info.get('type')
        else:
            volume_size = None
            volume_type = None

        if 'restorePoint' in body['instance']:
            backupRef = body['instance']['restorePoint']['backupRef']
            backup_id = utils.get_id_from_href(backupRef)
        else:
            backup_id = None

        availability_zone = body['instance'].get('availability_zone')
        nics = body['instance'].get('nics')

        slave_of_id = body['instance'].get('replica_of',
                                           # also check for older name
                                           body['instance'].get('slave_of'))
        replica_count = body['instance'].get('replica_count')
        instance = models.Instance.create(context, name, flavor_id,
                                          image_id, databases, users,
                                          datastore, datastore_version,
                                          volume_size, backup_id,
                                          availability_zone, nics,
                                          configuration, slave_of_id,
                                          replica_count=replica_count,
                                          volume_type=volume_type)

        view = views.InstanceDetailView(instance, req=req)
        return wsgi.Result(view.data(), 200)
Exemplo n.º 20
0
 def instance_root_create(self,
                          req,
                          body,
                          instance_id,
                          cluster_instances=None):
     LOG.info(_LI("Enabling root for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     user_name = context.user
     if body:
         password = body['password'] if 'password' in body else None
     else:
         password = None
     root = models.VerticaRoot.create(context, instance_id, user_name,
                                      password, cluster_instances)
     return wsgi.Result(views.RootCreatedView(root).data(), 200)
Exemplo n.º 21
0
 def index_all_master(self, req, tenant_id):
     """Return all instances that has no slave node."""
     LOG.info(_LI("Listing database instances with no slave for tenant '%s'"), tenant_id)
     LOG.debug("req : '%s'\n\n", req)
     context = req.environ[wsgi.CONTEXT_KEY]
     clustered_q = req.GET.get('include_clustered', '').lower()
     include_clustered = clustered_q == 'true'
     servers, marker = models.Instances.load(context, include_clustered)
     view = views.MasterInstancesView(servers, req=req)
     return wsgi.Result(view.data(), 200)
Exemplo n.º 22
0
 def backups(self, req, tenant_id, id):
     """Return all backups for the specified instance."""
     LOG.info(_LI("Listing backups for instance '%s'"), id)
     LOG.debug("req : '%s'\n\n", req)
     context = req.environ[wsgi.CONTEXT_KEY]
     backups, marker = backup_model.list_for_instance(context, id)
     view = backup_views.BackupViews(backups)
     paged = pagination.SimplePaginatedDataView(req.url, 'backups', view,
                                                marker)
     return wsgi.Result(paged.data(), 200)
Exemplo n.º 23
0
    def create(self, req, body, tenant_id):
        # TODO(hub-cap): turn this into middleware
        LOG.info(_LI("Creating a database instance for tenant '%s'"),
                 tenant_id)
        LOG.debug("req : '%s'\n\n", strutils.mask_password(req))
        LOG.debug("body : '%s'\n\n", strutils.mask_password(body))
        context = req.environ[wsgi.CONTEXT_KEY]
        datastore_args = body['instance'].get('datastore', {})
        datastore, datastore_version = (
            datastore_models.get_datastore_version(**datastore_args))
        image_id = datastore_version.image_id
        name = body['instance']['name']
        flavor_ref = body['instance']['flavorRef']
        flavor_id = utils.get_id_from_href(flavor_ref)

        configuration = self._configuration_parse(context, body)
        databases = populate_validated_databases(
            body['instance'].get('databases', []))
        database_names = [database.get('_name', '') for database in databases]
        users = None
        try:
            users = populate_users(body['instance'].get('users', []),
                                   database_names)
        except ValueError as ve:
            raise exception.BadRequest(msg=ve)

        if 'volume' in body['instance']:
            volume_size = int(body['instance']['volume']['size'])
        else:
            volume_size = None

        if 'restorePoint' in body['instance']:
            backupRef = body['instance']['restorePoint']['backupRef']
            backup_id = utils.get_id_from_href(backupRef)
        else:
            backup_id = None

        availability_zone = body['instance'].get('availability_zone')
        nics = body['instance'].get('nics')

        slave_of_id = body['instance'].get('replica_of',
                                           # also check for older name
                                           body['instance'].get('slave_of'))
        replica_count = body['instance'].get('replica_count')
        instance = models.Instance.create(context, name, flavor_id,
                                          image_id, databases, users,
                                          datastore, datastore_version,
                                          volume_size, backup_id,
                                          availability_zone, nics,
                                          configuration, slave_of_id,
                                          replica_count=replica_count)

        view = views.InstanceDetailView(instance, req=req)
        return wsgi.Result(view.data(), 200)
Exemplo n.º 24
0
 def backups(self, req, tenant_id, id):
     """Return all backups for the specified instance."""
     LOG.info(_LI("Listing backups for instance '%s'"),
              id)
     LOG.debug("req : '%s'\n\n", req)
     context = req.environ[wsgi.CONTEXT_KEY]
     backups, marker = backup_model.list_for_instance(context, id)
     view = backup_views.BackupViews(backups)
     paged = pagination.SimplePaginatedDataView(req.url, 'backups', view,
                                                marker)
     return wsgi.Result(paged.data(), 200)
Exemplo n.º 25
0
 def delete(self, req, tenant_id, id):
     """Delete a single instance."""
     LOG.info(_LI("Deleting database instance '%(instance_id)s' for tenant "
                  "'%(tenant_id)s'"),
              {'instance_id': id, 'tenant_id': tenant_id})
     LOG.debug("req : '%s'\n\n", req)
     # TODO(hub-cap): turn this into middleware
     context = req.environ[wsgi.CONTEXT_KEY]
     instance = models.load_any_instance(context, id)
     instance.delete()
     # TODO(cp16net): need to set the return code correctly
     return wsgi.Result(None, 202)
Exemplo n.º 26
0
    def show(self, req, tenant_id, id):
        """Return a single instance."""
        LOG.info(_LI("Showing database instance '%(instance_id)s' for tenant "
                     "'%(tenant_id)s'"),
                 {'instance_id': id, 'tenant_id': tenant_id})
        LOG.debug("req : '%s'\n\n", req)

        context = req.environ[wsgi.CONTEXT_KEY]
        server = models.load_instance_with_guest(models.DetailInstance,
                                                 context, id)
        return wsgi.Result(views.InstanceDetailView(server,
                                                    req=req).data(), 200)
Exemplo n.º 27
0
 def delete(self, req, tenant_id, id):
     """Delete a single instance."""
     LOG.info(_LI("Deleting database instance '%(instance_id)s' for tenant "
                  "'%(tenant_id)s'"),
              {'instance_id': id, 'tenant_id': tenant_id})
     LOG.debug("req : '%s'\n\n", req)
     # TODO(hub-cap): turn this into middleware
     context = req.environ[wsgi.CONTEXT_KEY]
     instance = models.load_any_instance(context, id)
     instance.delete()
     # TODO(cp16net): need to set the return code correctly
     return wsgi.Result(None, 202)
Exemplo n.º 28
0
    def show(self, req, tenant_id, id):
        """Return a single instance."""
        LOG.info(_LI("Showing database instance '%(instance_id)s' for tenant "
                     "'%(tenant_id)s'"),
                 {'instance_id': id, 'tenant_id': tenant_id})
        LOG.debug("req : '%s'\n\n", req)

        context = req.environ[wsgi.CONTEXT_KEY]
        server = models.load_instance_with_info(models.DetailInstance,
                                                context, id)
        return wsgi.Result(views.InstanceDetailView(server,
                                                    req=req).data(), 200)
Exemplo n.º 29
0
 def index(self, req, tenant_id):
     """Return all instances."""
     LOG.info(_LI("Listing database instances for tenant '%s'"), tenant_id)
     LOG.debug("req : '%s'\n\n", req)
     context = req.environ[wsgi.CONTEXT_KEY]
     clustered_q = req.GET.get('include_clustered', '').lower()
     include_clustered = clustered_q == 'true'
     servers, marker = models.Instances.load(context, include_clustered)
     view = views.InstancesView(servers, req=req)
     paged = pagination.SimplePaginatedDataView(req.url, 'instances', view,
                                                marker)
     return wsgi.Result(paged.data(), 200)
Exemplo n.º 30
0
 def index(self, req, tenant_id):
     """Return all instances."""
     LOG.info(_LI("Listing database instances for tenant '%s'"), tenant_id)
     LOG.debug("req : '%s'\n\n", req)
     context = req.environ[wsgi.CONTEXT_KEY]
     clustered_q = req.GET.get('include_clustered', '').lower()
     include_clustered = clustered_q == 'true'
     servers, marker = models.Instances.load(context, include_clustered)
     view = views.InstancesView(servers, req=req)
     paged = pagination.SimplePaginatedDataView(req.url, 'instances', view,
                                                marker)
     return wsgi.Result(paged.data(), 200)
Exemplo n.º 31
0
 def configuration(self, req, tenant_id, id):
     """
     Returns the default configuration template applied to the instance.
     """
     LOG.info(_LI("Getting default configuration for instance %s"), id)
     context = req.environ[wsgi.CONTEXT_KEY]
     instance = models.Instance.load(context, id)
     LOG.debug("Server: %s", instance)
     config = instance.get_default_configuration_template()
     LOG.debug("Default config for instance %(instance_id)s is %(config)s",
               {'instance_id': id, 'config': config})
     return wsgi.Result(views.DefaultConfigurationView(
                        config).data(), 200)
Exemplo n.º 32
0
 def configuration(self, req, tenant_id, id):
     """
     Returns the default configuration template applied to the instance.
     """
     LOG.info(_LI("Getting default configuration for instance %s"), id)
     context = req.environ[wsgi.CONTEXT_KEY]
     instance = models.Instance.load(context, id)
     LOG.debug("Server: %s", instance)
     config = instance.get_default_configuration_template()
     LOG.debug("Default config for instance %(instance_id)s is %(config)s",
               {'instance_id': id, 'config': config})
     return wsgi.Result(views.DefaultConfigurationView(
                        config).data(), 200)
Exemplo n.º 33
0
    def index(self, req, tenant_id, instance_id):
        LOG.info(_LI("Listing databases for instance '%(id)s'\n"
                     "req : '%(req)s'\n\n") %
                 {"id": instance_id, "req": req})
        context = req.environ[wsgi.CONTEXT_KEY]
        self.authorize_target_action(context, 'database:index', instance_id)

        databases, next_marker = self.list_databases(context, instance_id)
        filtered_databases = filter(
            lambda database: not self.is_reserved_id(
                self.get_database_id(database)), databases)
        view = self.build_model_collection_view(
            filtered_databases).paginated(req.url, next_marker)

        return wsgi.Result(view.data(), 200)
Exemplo n.º 34
0
    def update(self, req, id, body, tenant_id):
        """Updates the instance to attach/detach configuration."""
        LOG.info(_LI("Updating database instance '%(instance_id)s' for tenant "
                     "'%(tenant_id)s'"),
                 {'instance_id': id, 'tenant_id': tenant_id})
        LOG.debug("req: %s", req)
        LOG.debug("body: %s", body)
        context = req.environ[wsgi.CONTEXT_KEY]

        instance = models.Instance.load(context, id)

        # Make sure args contains a 'configuration_id' argument,
        args = {}
        args['configuration_id'] = self._configuration_parse(context, body)
        self._modify_instance(context, req, instance, **args)
        return wsgi.Result(None, 202)
Exemplo n.º 35
0
    def update(self, req, id, body, tenant_id):
        """Updates the instance to attach/detach configuration."""
        LOG.info(_LI("Updating database instance '%(instance_id)s' for tenant "
                     "'%(tenant_id)s'"),
                 {'instance_id': id, 'tenant_id': tenant_id})
        LOG.debug("req: %s", req)
        LOG.debug("body: %s", body)
        context = req.environ[wsgi.CONTEXT_KEY]

        instance = models.Instance.load(context, id)

        # Make sure args contains a 'configuration_id' argument,
        args = {}
        args['configuration_id'] = self._configuration_parse(context, body)
        self._modify_instance(instance, **args)
        return wsgi.Result(None, 202)
Exemplo n.º 36
0
    def show(self, req, tenant_id, instance_id, id):
        LOG.info(_LI("Showing a database for instance '%(id)s'\n"
                     "req : '%(req)s'\n\n") %
                 {"id": instance_id, "req": req})
        context = req.environ[wsgi.CONTEXT_KEY]
        self.authorize_target_action(context, 'database:show', instance_id)

        database_id = correct_id_with_req(id, req)
        client = self.create_guest_client(context, instance_id)
        try:
            if self.is_reserved_id(database_id):
                raise exception.ReservedDatabaseId(name=database_id)

            model = self.find_database(client, database_id)
            if not model:
                raise exception.DatabaseNotFound(uuid=database_id)

            view = self.build_model_view(model)

            return wsgi.Result(view.data(), 200)
        except (ValueError, AttributeError) as e:
            raise exception.BadRequest(str(e))
Exemplo n.º 37
0
 def delete(self, req, tenant_id, id):
     """Delete a single instance."""
     LOG.info(_LI("Deleting database instance '%(instance_id)s' for tenant "
                  "'%(tenant_id)s'"),
              {'instance_id': id, 'tenant_id': tenant_id})
     LOG.debug("req : '%s'\n\n", req)
     context = req.environ[wsgi.CONTEXT_KEY]
     instance = models.load_any_instance(context, id)
     context.notification = notification.DBaaSInstanceDelete(
         context, request=req)
     with StartNotification(context, instance_id=instance.id):
         marker = 'foo'
         while marker:
             instance_modules, marker = module_models.InstanceModules.load(
                 context, instance_id=id)
             for instance_module in instance_modules:
                 instance_module = module_models.InstanceModule.load(
                     context, instance_module['instance_id'],
                     instance_module['module_id'])
                 module_models.InstanceModule.delete(
                     context, instance_module)
         instance.delete()
     return wsgi.Result(None, 202)
Exemplo n.º 38
0
 def delete(self, req, tenant_id, id):
     """Delete a single instance."""
     LOG.info(_LI("Deleting database instance '%(instance_id)s' for tenant "
                  "'%(tenant_id)s'"),
              {'instance_id': id, 'tenant_id': tenant_id})
     LOG.debug("req : '%s'\n\n", req)
     context = req.environ[wsgi.CONTEXT_KEY]
     instance = models.load_any_instance(context, id)
     context.notification = notification.DBaaSInstanceDelete(
         context, request=req)
     with StartNotification(context, instance_id=instance.id):
         marker = 'foo'
         while marker:
             instance_modules, marker = module_models.InstanceModules.load(
                 context, instance_id=id)
             for instance_module in instance_modules:
                 instance_module = module_models.InstanceModule.load(
                     context, instance_module['instance_id'],
                     instance_module['module_id'])
                 module_models.InstanceModule.delete(
                     context, instance_module)
         instance.delete()
     return wsgi.Result(None, 202)
Exemplo n.º 39
0
    def edit(self, req, id, body, tenant_id):
        """
        Updates the instance to set or unset one or more attributes.
        """
        LOG.info(_LI("Editing instance for tenant id %s."), tenant_id)
        LOG.debug("req: %s", logging.mask_password(req))
        LOG.debug("body: %s", logging.mask_password(body))
        context = req.environ[wsgi.CONTEXT_KEY]

        instance = models.Instance.load(context, id)

        if 'slave_of' in body['instance']:
            LOG.debug("Detaching replica from source.")
            instance.detach_replica()

        # If configuration is set, then we will update the instance to
        # use the new configuration. If configuration is empty, we
        # want to disassociate the instance from the configuration
        # group and remove the active overrides file.
        # If instance name is set, then we will update the instance name.

        edit_args = {}
        if 'configuration' in body['instance']:
            configuration_id = self._configuration_parse(context, body)
            if configuration_id:
                instance.assign_configuration(configuration_id)
            else:
                instance.unassign_configuration()
            edit_args['configuration_id'] = configuration_id

        if 'name' in body['instance']:
            edit_args['name'] = body['instance']['name']

        if edit_args:
            instance.update_db(**edit_args)

        return wsgi.Result(None, 202)
Exemplo n.º 40
0
    def create(self, req, body, tenant_id, instance_id):
        LOG.info(_LI("Creating users for instance '%(id)s'\n"
                     "req : '%(req)s'\n\n"
                     "body: '%(body)s'\n'n") %
                 {"id": instance_id,
                  "req": strutils.mask_password(req),
                  "body": strutils.mask_password(body)})
        context = req.environ[wsgi.CONTEXT_KEY]
        self.authorize_target_action(context, 'user:create', instance_id)

        context.notification = notification.DBaaSUserCreate(context,
                                                            request=req)
        users = body['users']
        usernames = [user['name'] for user in users]
        client = self.create_guest_client(context, instance_id)
        with StartNotification(context, instance_id=instance_id,
                               username="******".join(usernames)):

            try:
                user_models = self.parse_users_from_request(users)
                unique_user_ids = set()
                for model in user_models:
                    user_id = self.get_user_id(model)
                    if self.is_reserved_id(user_id):
                        raise exception.ReservedUserId(name=user_id)
                    if user_id in unique_user_ids:
                        raise exception.DuplicateUserId(name=user_id)
                    if self.find_user(client, user_id):
                        raise exception.UserAlreadyExists(name=user_id)
                    unique_user_ids.add(user_id)

                self.create_users(client, user_models)
            except (ValueError, AttributeError) as e:
                raise exception.BadRequest(str(e))

        return wsgi.Result(None, 202)
Exemplo n.º 41
0
    def create(self, req, body, tenant_id, instance_id):
        LOG.info(_LI("Creating databases for instance '%(id)s'\n"
                     "req : '%(req)s'\n\n"
                     "body: '%(body)s'\n'n") %
                 {"id": instance_id,
                  "req": strutils.mask_password(req),
                  "body": strutils.mask_password(body)})
        context = req.environ[wsgi.CONTEXT_KEY]
        self.authorize_target_action(context, 'database:create', instance_id)

        context.notification = notification.DBaaSDatabaseCreate(context,
                                                                request=req)
        databases = body['databases']
        dbnames = [database['name'] for database in databases]
        client = self.create_guest_client(context, instance_id)
        with StartNotification(context, instance_id=instance_id,
                               dbname=",".join(dbnames)):

            try:
                database_models = self.parse_databases_from_request(databases)
                unique_database_ids = set()
                for model in database_models:
                    database_id = self.get_database_id(model)
                    if self.is_reserved_id(database_id):
                        raise exception.ReservedDatabaseId(name=database_id)
                    if database_id in unique_database_ids:
                        raise exception.DuplicateDatabaseId(name=database_id)
                    if self.find_database(client, database_id):
                        raise exception.DatabaseAlreadyExists(name=database_id)
                    unique_database_ids.add(database_id)

                self.create_databases(client, database_models)
            except (ValueError, AttributeError) as e:
                raise exception.BadRequest(str(e))

        return wsgi.Result(None, 202)
Exemplo n.º 42
0
    def create(self, req, body, tenant_id):
        # TODO(hub-cap): turn this into middleware
        LOG.info(_LI("Creating a database instance for tenant '%s'"),
                 tenant_id)
        LOG.debug("req : '%s'\n\n", strutils.mask_password(req))
        LOG.debug("body : '%s'\n\n", strutils.mask_password(body))
        context = req.environ[wsgi.CONTEXT_KEY]
        context.notification = notification.DBaaSInstanceCreate(context,
                                                                request=req)
        datastore_args = body['instance'].get('datastore', {})
        datastore, datastore_version = (datastore_models.get_datastore_version(
            **datastore_args))
        image_id = datastore_version.image_id
        name = body['instance']['name']
        flavor_ref = body['instance']['flavorRef']
        flavor_id = utils.get_id_from_href(flavor_ref)

        configuration = self._configuration_parse(context, body)
        databases = populate_validated_databases(body['instance'].get(
            'databases', []))
        database_names = [database.get('_name', '') for database in databases]
        users = None
        try:
            users = populate_users(body['instance'].get('users', []),
                                   database_names)
        except ValueError as ve:
            raise exception.BadRequest(msg=ve)

        if 'volume' in body['instance']:
            volume_info = body['instance']['volume']
            volume_size = int(volume_info['size'])
            volume_type = volume_info.get('type')
        else:
            volume_size = None
            volume_type = None

        if 'restorePoint' in body['instance']:
            backupRef = body['instance']['restorePoint']['backupRef']
            backup_id = utils.get_id_from_href(backupRef)
        else:
            backup_id = None

        availability_zone = body['instance'].get('availability_zone')
        nics = body['instance'].get('nics')

        slave_of_id = body['instance'].get(
            'replica_of',
            # also check for older name
            body['instance'].get('slave_of'))
        replica_count = body['instance'].get('replica_count')
        modules = body['instance'].get('modules')
        locality = body['instance'].get('locality')
        if locality:
            locality_domain = ['affinity', 'anti-affinity']
            locality_domain_msg = ("Invalid locality '%s'. "
                                   "Must be one of ['%s']" %
                                   (locality, "', '".join(locality_domain)))
            if locality not in locality_domain:
                raise exception.BadRequest(msg=locality_domain_msg)
            if slave_of_id:
                dupe_locality_msg = (
                    'Cannot specify locality when adding replicas to existing '
                    'master.')
                raise exception.BadRequest(msg=dupe_locality_msg)

        instance = models.Instance.create(context,
                                          name,
                                          flavor_id,
                                          image_id,
                                          databases,
                                          users,
                                          datastore,
                                          datastore_version,
                                          volume_size,
                                          backup_id,
                                          availability_zone,
                                          nics,
                                          configuration,
                                          slave_of_id,
                                          replica_count=replica_count,
                                          volume_type=volume_type,
                                          modules=modules,
                                          locality=locality)

        view = views.InstanceDetailView(instance, req=req)
        return wsgi.Result(view.data(), 200)
Exemplo n.º 43
0
    def create(self, req, body, tenant_id):
        # TODO(hub-cap): turn this into middleware
        LOG.info(_LI("Creating a database instance for tenant '%s'"),
                 tenant_id)
        LOG.debug("req : '%s'\n\n", strutils.mask_password(req))
        LOG.debug("body : '%s'\n\n", strutils.mask_password(body))
        context = req.environ[wsgi.CONTEXT_KEY]
        policy.authorize_on_tenant(context, 'instance:create')
        context.notification = notification.DBaaSInstanceCreate(context,
                                                                request=req)
        datastore_args = body['instance'].get('datastore', {})
        datastore, datastore_version = (datastore_models.get_datastore_version(
            **datastore_args))
        image_id = datastore_version.image_id
        name = body['instance']['name']
        flavor_ref = body['instance']['flavorRef']
        flavor_id = utils.get_id_from_href(flavor_ref)

        configuration = self._configuration_parse(context, body)
        databases = populate_validated_databases(body['instance'].get(
            'databases', []))
        database_names = [database.get('_name', '') for database in databases]
        users = None
        try:
            users = populate_users(body['instance'].get('users', []),
                                   database_names)
        except ValueError as ve:
            raise exception.BadRequest(msg=ve)

        modules = body['instance'].get('modules')

        # The following operations have their own API calls.
        # We need to make sure the same policies are enforced when
        # creating an instance.
        # i.e. if attaching configuration group to an existing instance is not
        # allowed, it should not be possible to create a new instance with the
        # group attached either
        if configuration:
            policy.authorize_on_tenant(context, 'instance:update')
        if modules:
            policy.authorize_on_tenant(context, 'instance:module_apply')
        if users:
            policy.authorize_on_tenant(context,
                                       'instance:extension:user:create')
        if databases:
            policy.authorize_on_tenant(context,
                                       'instance:extension:database:create')

        if 'volume' in body['instance']:
            volume_info = body['instance']['volume']
            volume_size = int(volume_info['size'])
            volume_type = volume_info.get('type')
        else:
            volume_size = None
            volume_type = None

        if 'restorePoint' in body['instance']:
            backupRef = body['instance']['restorePoint']['backupRef']
            backup_id = utils.get_id_from_href(backupRef)
        else:
            backup_id = None

        availability_zone = body['instance'].get('availability_zone')
        nics = body['instance'].get('nics')

        slave_of_id = body['instance'].get(
            'replica_of',
            # also check for older name
            body['instance'].get('slave_of'))
        replica_count = body['instance'].get('replica_count')
        locality = body['instance'].get('locality')
        if locality:
            locality_domain = ['affinity', 'anti-affinity']
            locality_domain_msg = ("Invalid locality '%s'. "
                                   "Must be one of ['%s']" %
                                   (locality, "', '".join(locality_domain)))
            if locality not in locality_domain:
                raise exception.BadRequest(msg=locality_domain_msg)
            if slave_of_id:
                dupe_locality_msg = (
                    'Cannot specify locality when adding replicas to existing '
                    'master.')
                raise exception.BadRequest(msg=dupe_locality_msg)
        region_name = body['instance'].get('region_name', CONF.os_region_name)

        instance = models.Instance.create(context,
                                          name,
                                          flavor_id,
                                          image_id,
                                          databases,
                                          users,
                                          datastore,
                                          datastore_version,
                                          volume_size,
                                          backup_id,
                                          availability_zone,
                                          nics,
                                          configuration,
                                          slave_of_id,
                                          replica_count=replica_count,
                                          volume_type=volume_type,
                                          modules=modules,
                                          locality=locality,
                                          region_name=region_name)

        view = views.InstanceDetailView(instance, req=req)
        return wsgi.Result(view.data(), 200)
Exemplo n.º 44
0
 def instance_root_index(self, req, tenant_id, instance_id):
     LOG.info(_LI("Getting root enabled for instance '%s'.") % instance_id)
     LOG.info(_LI("req : '%s'\n\n") % req)
     context = req.environ[wsgi.CONTEXT_KEY]
     is_root_enabled = models.VerticaRoot.load(context, instance_id)
     return wsgi.Result(views.RootEnabledView(is_root_enabled).data(), 200)
Exemplo n.º 45
0
 def cluster_root_index(self, req, tenant_id, cluster_id):
     LOG.info(_LI("Getting root enabled for cluster '%s'.") % cluster_id)
     instance_id, cluster_instances = self._get_cluster_instance_id(
         tenant_id, cluster_id)
     return self.instance_root_index(req, tenant_id, instance_id)
Exemplo n.º 46
0
 def cluster_root_create(self, req, body, tenant_id, cluster_id):
     LOG.info(_LI("Enabling root for cluster '%s'.") % cluster_id)
     instance_id, cluster_instances = self._get_cluster_instance_id(
         tenant_id, cluster_id)
     return self.instance_root_create(req, body, instance_id,
                                      cluster_instances)
Exemplo n.º 47
0
 def cluster_root_index(self, req, tenant_id, cluster_id):
     LOG.info(_LI("Getting root enabled for cluster '%s'.") % cluster_id)
     single_instance_id, cluster_instances = self._get_cluster_instance_id(
         tenant_id, cluster_id)
     return self.instance_root_index(req, tenant_id, single_instance_id)
Exemplo n.º 48
0
 def cluster_root_create(self, req, body, tenant_id, cluster_id):
     LOG.info(_LI("Enabling root for cluster '%s'.") % cluster_id)
     single_instance_id, cluster_instances = self._get_cluster_instance_id(
         tenant_id, cluster_id)
     return self.instance_root_create(req, body, single_instance_id,
                                      cluster_instances)