operations.py 6.5 KB
Newer Older
1 2
from logging import getLogger

3 4 5 6 7
from .models import activity_context

from django.core.exceptions import PermissionDenied


8 9 10
logger = getLogger(__name__)


11 12 13 14 15
class Operation(object):
    """Base class for VM operations.
    """
    async_queue = 'localhost.man'
    required_perms = ()
16
    do_not_call_in_templates = True
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

    def __call__(self, **kwargs):
        return self.call(**kwargs)

    def __init__(self, subject):
        """Initialize a new operation bound to the specified subject.
        """
        self.subject = subject

    def __unicode__(self):
        return self.name

    def __prelude(self, kwargs):
        """This method contains the shared prelude of call and async.
        """
32
        skip_auth_check = kwargs.setdefault('system', False)
33
        user = kwargs.setdefault('user', None)
34 35
        parent_activity = kwargs.pop('parent_activity', None)

36
        if not skip_auth_check:
37 38
            self.check_auth(user)
        self.check_precond()
39
        return self.create_activity(parent=parent_activity, user=user)
40 41 42 43 44 45

    def _exec_op(self, activity, user, **kwargs):
        """Execute the operation inside the specified activity's context.
        """
        with activity_context(activity, on_abort=self.on_abort,
                              on_commit=self.on_commit):
46
            return self._operation(activity=activity, user=user, **kwargs)
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

    def _operation(self, activity, user, system, **kwargs):
        """This method is the operation's particular implementation.

        Deriving classes should implement this method.
        """
        raise NotImplementedError

    def async(self, **kwargs):
        """Execute the operation asynchronously.

        Only a quick, preliminary check is ran before creating the associated
        activity and queuing the job.

        The returned value is the handle for the asynchronous job.

        For more information, check the synchronous call's documentation.
        """
65 66
        logger.info("%s called asynchronously with the following parameters: "
                    "%r", self.__class__.__name__, kwargs)
67 68 69 70 71 72 73 74 75 76 77
        activity = self.__prelude(kwargs)
        return self.async_operation.apply_async(args=(self.id,
                                                      self.subject.pk,
                                                      activity.pk),
                                                kwargs=kwargs,
                                                queue=self.async_queue)

    def call(self, **kwargs):
        """Execute the operation (synchronously).

        Anticipated keyword arguments:
78 79 80
        * parent_activity: Parent activity for the operation. If this argument
                           is present, the operation's activity will be created
                           as a child activity of it.
81 82 83
        * system: Indicates that the operation is invoked by the system, not a
                  User. If this argument is present and has a value of True,
                  then authorization checks are skipped.
84 85
        * user: The User invoking the operation. If this argument is not
                present, it'll be provided with a default value of None.
86
        """
87 88
        logger.info("%s called (synchronously) with the following parameters: "
                    "%r", self.__class__.__name__, kwargs)
89 90 91 92 93 94 95 96 97 98 99
        activity = self.__prelude(kwargs)
        return self._exec_op(activity=activity, **kwargs)

    def check_precond(self):
        pass

    def check_auth(self, user):
        if not user.has_perms(self.required_perms):
            raise PermissionDenied("%s doesn't have the required permissions."
                                   % user)

100
    def create_activity(self, parent, user):
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        raise NotImplementedError

    def on_abort(self, activity, error):
        """This method is called when the operation aborts (i.e. raises an
        exception).
        """
        pass

    def on_commit(self, activity):
        """This method is called when the operation executes successfully.
        """
        pass


operation_registry_name = '_ops'


class OperatedMixin(object):
    def __getattr__(self, name):
        # NOTE: __getattr__ is only called if the attribute doesn't already
        # exist in your __dict__
        cls = self.__class__
        ops = getattr(cls, operation_registry_name, {})
        op = ops.get(name)
        if op:
            return op(self)
        else:
            raise AttributeError("%r object has no attribute %r" %
                                 (self.__class__.__name__, name))

131 132 133 134 135 136 137 138 139 140 141 142 143
    def get_available_operations(self, user):
        """Yield Operations that match permissions of user and preconditions.
        """
        for name in getattr(self, operation_registry_name, {}):
            try:
                op = getattr(self, name)
                op.check_auth(user)
                op.check_precond()
            except:
                pass  # unavailable
            else:
                yield op

144

145
def register_operation(op_cls, op_id=None, target_cls=None):
146 147 148 149 150 151
    """Register the specified operation with the target class.

    You can optionally specify an ID to be used for the registration;
    otherwise, the operation class' 'id' attribute will be used.
    """
    if op_id is None:
152 153 154 155 156 157 158 159
        try:
            op_id = op_cls.id
        except AttributeError:
            raise NotImplementedError("Operations should specify an 'id' "
                                      "attribute designating the name the "
                                      "operation can be called by on its "
                                      "host. Alternatively, provide the name "
                                      "in the 'op_id' parameter to this call.")
160

161 162 163 164 165 166 167 168 169 170 171
    if target_cls is None:
        try:
            target_cls = op_cls.host_cls
        except AttributeError:
            raise NotImplementedError("Operations should specify a 'host_cls' "
                                      "attribute designating the host class "
                                      "the operation should be registered to. "
                                      "Alternatively, provide the host class "
                                      "in the 'target_cls' parameter to this "
                                      "call.")

172 173 174 175 176 177 178 179
    if not issubclass(target_cls, OperatedMixin):
        raise TypeError("%r is not a subclass of %r" %
                        (target_cls.__name__, OperatedMixin.__name__))

    if not hasattr(target_cls, operation_registry_name):
        setattr(target_cls, operation_registry_name, dict())

    getattr(target_cls, operation_registry_name)[op_id] = op_cls