Пример #1
0
    def execute(self, args):
        for path in args.paths:
            obj_dir = self.current_obj

            # cleanup trailing slash
            if path.endswith('/'):
                path = path[:-1]

            if os.path.dirname(path):
                obj_dir = self.traverse(os.path.dirname(path))

            obj = obj_dir[os.path.basename(path)]

            if not obj_dir or not obj:
                self.write("No such object: %s\n" % path)
                continue

            parent = obj.__parent__
            del obj_dir[obj.__name__]

            try:
                handle(obj, ModelDeletedEvent(parent))
            except Exception:
                if not args.f:
                    raise
Пример #2
0
def init(test=False):
    global _db, _testing

    if _db and not test:
        return

    log.info("Initializing zodb")
    handle(BeforeDatabaseInitalizedEvent())

    if not test:
        storage_type = get_config().get('db', 'storage_type')

        if storage_type == 'zeo':
            from ZODB import DB
            storage = ClientStorage('%s/socket' % get_db_dir())
            _db = DB(storage)
        elif storage_type == 'embedded':
            from ZODB import DB
            storage = FileStorage('%s/data.fs' % get_db_dir())
            _db = DB(storage)
        elif storage_type == 'memory':
            from ZODB.tests.util import DB
            _db = DB()
        else:
            raise Exception("Unknown storage type '%s'" % storage_type)
    else:
        from ZODB.tests.util import DB
        _db = DB()
        _testing = True

    init_schema()
def demo_events(load_zcml):
    gsm = getGlobalSiteManager()

    if load_zcml:
        from zope.configuration.xmlconfig import xmlconfig
        fname = __file__[:-3] + '.zcml'
        xmlconfig(open(fname))
    else:
        gsm.registerHandler(me.handle_some_event)
        gsm.registerHandler(me.handle_object_modified_event,
                            [me.IData, me.IObjectModifiedEvent])

    obj = me.Data()
    evt = me.SomeEvent()
    evt.object = obj

    if load_zcml:
        notify(evt)
    else:
        handle(evt)

    assert obj.data == 'changed'

    obj.data = 'unchanged'

    if load_zcml:
        notify(me.ObjectModifiedEvent(obj))
    else:
        objectEventNotify(me.ObjectModifiedEvent(obj))

    assert obj.data == 'changed'

    print "Done"
Пример #4
0
 def __init__(self):
     """Initialize the transaction.  If this is the first transaction in
     the stack, a TransactionBegin event is emited."""
     
     self._need_rollback = False
     if not self._stack:
         component.handle(TransactionBegin())
     self._stack.append(self)
Пример #5
0
    def set_owner(self, principal):
        prinrole = interfaces.IPrincipalRoleManager(self)
        oldowner = self.__owner__
        prinrole.unsetRoleForPrincipal('owner', oldowner)
        prinrole.assignRoleToPrincipal('owner', principal.id)

        if (not hasattr(self, '__suppress_events') and
                principal is not None and principal.id != oldowner):
            handle(self, OwnerChangedEvent(oldowner, principal.id))
Пример #6
0
 def rollback(self):
     """Roll-back the transaction.  First, the transaction is closed.
     Every transaction on the stack is then marked for roll-back.  If
     the stack is empty, a TransactionRollback event is emited."""
     
     self._close()
     for tx in self._stack:
         tx._need_rollback = True
     if not self._stack:
         component.handle(TransactionRollback())
Пример #7
0
    def _verifyImport(self, obj):
        adapted = queryAdapter(object(), IAnotherDummy2)
        self.failUnless(IAnotherDummy2.providedBy(adapted))
        self.failUnless(adapted.verify())

        adapted = queryAdapter(object(), IAnotherDummy2, name=u'foo')
        self.failUnless(IAnotherDummy2.providedBy(adapted))
        self.failUnless(adapted.verify())

        dummy = DummyObject()
        results = [adap.verify() for adap in
                        subscribers([dummy], IAnotherDummy2)]
        self.assertEquals(results, [True])

        dummy = DummyObject()
        handle(dummy)
        self.assertEquals(dummy.handled, 1)

        util = queryUtility(IDummyInterface2, name=u'foo')
        self.failUnless(IDummyInterface.providedBy(util))
        self.failUnless(util.verify())
        self.failUnless(util.__parent__ == obj)
        name = ('Products.GenericSetup.tests.test_components.'
                    'IDummyInterface2-foo')
        self.assertEquals(util.__name__, name)
        self.failUnless(name in obj.objectIds())

        util = queryUtility(IDummyInterface)
        self.failUnless(IDummyInterface.providedBy(util))
        self.failUnless(util.verify())
        self.failUnless(util.__parent__ == obj)
        name = 'dummy_utility'
        self.assertEquals(util.__name__, name)
        self.failUnless(name in obj.objectIds())

        util = queryUtility(IDummyInterface, name='dummy tool name')
        self.failUnless(IDummyInterface.providedBy(util))
        self.failUnless(util.verify())
        self.assertEqual(util.meta_type, 'dummy tool')

        # make sure we can get the tool by normal means
        tool = getattr(obj.aq_parent, 'dummy_tool')
        self.assertEqual(tool.meta_type, 'dummy tool')
        self.assertEquals(repr(aq_base(util)), repr(aq_base(tool)))

        util = queryUtility(IDummyInterface2, name='dummy tool name2')
        self.failUnless(IDummyInterface2.providedBy(util))
        self.failUnless(util.verify())
        self.assertEqual(util.meta_type, 'dummy tool2')

        # make sure we can get the tool by normal means
        tool = getattr(obj.aq_parent, 'dummy_tool2')
        self.assertEqual(tool.meta_type, 'dummy tool2')
        self.assertEquals(repr(aq_base(util)), repr(aq_base(tool)))
Пример #8
0
 def commit(self):
     """Commit the transaction.  First, the transaction is closed.
     If it needs to be rolled-back, a TransactionRollback event is emited.
     Otherwise, a TransactionCommit event is emited."""
     
     self._close()
     if not self._stack:
         if self._need_rollback:
             component.handle(TransactionRollback())
         else:
             component.handle(TransactionCommit())
Пример #9
0
def new_local_site_dispatcher(event):
    """
    Dispatches just like an object event,
    that way we can do things based on the type of the
    site manager.

    Note that if the containing ISite is (re)moved, an
    ObjectEvent will be fired for (sitemanager, site-event);
    that is, you subscribe to the site manager and the object moved
    event, but the event will have the ISite as the object property.
    """
    component.handle(event.manager, event)
Пример #10
0
def notifyFieldEvent(event):
    field = event.field
    if IFieldRenderEvent.providedBy(event):
        event.value = getMultiAdapter((field, event), IFieldValue)
        if event.kwargs.get('raw', False) or getattr(event, 'raw', False):
            # bail out
            return

    handle(event.field, event.instance, event)

    if IFieldStorageEvent.providedBy(event):
        for ignore in subscribers((field, event), IFieldValueSetter):
            pass
Пример #11
0
    def add(self, item):
        if not self.can_contain(item):
            raise Exception("Can only contain instances or providers of %s" % self.__contains__.__name__)

        old_parent = item.__parent__
        res = self._add(item)

        if not hasattr(self, '__suppress_events'):
            if old_parent is not None and old_parent is not self:
                handle(item, ModelMovedEvent(item.__parent__, self))
            else:
                handle(item, ModelCreatedEvent(self))
        return res
Пример #12
0
def before_object_assigned_event_dispatcher(event):
    """
    Listens for :mod:`zope.schema` fields to fire
    :class:`~nti.schema.interfaces.IBeforeSchemaFieldAssignedEvent`, and re-dispatches
    these events based on the value being assigned, the object being
    assigned to, and of course the event (note that
    :class:`~zope.schema.interfaces.IBeforeObjectAssignedEvent` is a
    sub-interface of :class:`~nti.schema.interfaces.IBeforeSchemaFieldAssignedEvent`).

    This is analogous to
    :func:`zope.component.event.objectEventNotify`
    """
    handle(event.object, event.context, event)
Пример #13
0
    def render_DELETE(self, request):
        force = request.args.get('force', ['false'])[0] == 'true'

        parent = self.context.__parent__
        del parent[self.context.__name__]

        try:
            handle(self.context, ModelDeletedEvent(parent))
        except Exception as e:
            if not force:
                raise e
            return {'status': 'failure'}

        return {'status': 'success'}
Пример #14
0
def main():
    gsm.registerHandler(docCreated)
    gsm.registerHandler(docCreated2)

    documents = (('doc1', Document('a document one', 'Всем привет. Буквально пару слов обо мне.')),
                 ('doc2', Document('a document two', 'Сейчас я переехал в Германию и работаю в InnoGames.')),
                 ('doc3', Document('a document three', 'И сегодня мы поговорим с вами.')))
    # create documents
    for _, d in documents:
        sleep(0.5)
        handle(DocumentCreated(d))

    print('attributes of created documents:')
    for n, d in documents:
        print('Document {!r}'.format(n))
        print_attrs(d)
        print()
Пример #15
0
    def test_remove_components(self):
        from Products.GenericSetup.components import importComponentRegistry

        obj = self._obj
        self._populate(obj)
        self._verifyImport(obj)

        context = DummyImportContext(obj, False)
        context._files['componentregistry.xml'] = _REMOVE_IMPORT
        importComponentRegistry(context)

        adapted = queryAdapter(object(), IAnotherDummyInterface2)
        self.failUnless(adapted is None)

        # This one should still exist
        adapted = queryAdapter(object(), IAnotherDummyInterface2, name=u'foo')
        self.failIf(adapted is None)

        dummy = DummyObject()
        results = [
            adap.verify()
            for adap in subscribers([dummy], IAnotherDummyInterface2)
        ]
        self.assertEquals(results, [])

        dummy = DummyObject()
        handle(dummy)
        self.assertEquals(dummy.handled, 0)

        util = queryUtility(IDummyInterface2, name=u'foo')
        name = 'Products.GenericSetup.tests.test_components.IDummyInterface2-foo'
        self.failUnless(util is None)
        self.failIf(name in obj.objectIds())

        util = queryUtility(IDummyInterface)
        self.failUnless(util is None)
        self.failIf('dummy_utility' in obj.objectIds())

        util = queryUtility(IDummyInterface, name='dummy tool name')
        self.failUnless(util is None)

        # This one should still exist
        util = queryUtility(IDummyInterface2, name='dummy tool name2')
        self.failIf(util is None)
Пример #16
0
    def test_remove_components(self):
        from Products.GenericSetup.components import importComponentRegistry

        obj = self._obj
        self._populate(obj)
        self._verifyImport(obj)

        context = DummyImportContext(obj, False)
        context._files['componentregistry.xml'] = _REMOVE_IMPORT
        importComponentRegistry(context)

        adapted = queryAdapter(object(), IAnotherDummy2)
        self.failUnless(adapted is None)

        # This one should still exist
        adapted = queryAdapter(object(), IAnotherDummy2, name=u'foo')
        self.failIf(adapted is None)

        dummy = DummyObject()
        results = [adap.verify() for adap in
                        subscribers([dummy], IAnotherDummy2)]
        self.assertEquals(results, [])

        dummy = DummyObject()
        handle(dummy)
        self.assertEquals(dummy.handled, 0)

        util = queryUtility(IDummyInterface2, name=u'foo')
        name = ('Products.GenericSetup.tests.test_components.'
                    'IDummyInterface2-foo')
        self.failUnless(util is None)
        self.failIf(name in obj.objectIds())

        util = queryUtility(IDummyInterface)
        self.failUnless(util is None)
        self.failIf('dummy_utility' in obj.objectIds())

        util = queryUtility(IDummyInterface, name='dummy tool name')
        self.failUnless(util is None)

        # This one should still exist
        util = queryUtility(IDummyInterface2, name='dummy tool name2')
        self.failIf(util is None)
Пример #17
0
class TmpObj(object):
    """A proxy for storing and remembering temporary modifications to
    objects, and later applying them to the wrapped object.

    """

    __allowed_attrs__ = ['__markers__']

    def __init__(self, wrapped, cls=None):
        self.__dict__['obj'] = wrapped
        self.__dict__['cls'] = cls
        self.__dict__['modified_attrs'] = {}

    def __getattr__(self, name):
        if name.startswith('__') and name not in TmpObj.__allowed_attrs__:
            raise AttributeError(name)
        if name in self.__dict__['modified_attrs']:
            return self.__dict__['modified_attrs'][name]
        else:
            obj = self.__dict__['obj']
            if not obj:
                # try to access class methods
                cls_method = getattr(self.__dict__['cls'], name, None)
                return cls_method if inspect.isroutine(cls_method) else None
            return getattr(obj, name) if obj else None

    def __setattr__(self, name, value):
        if getattr(self, name, object()) != value:
            self.__dict__['modified_attrs'][name] = value

    # ingore_readonly is needed to restore objects with readonly fields
    # using importexport without issues. It really makes it ignore all
    # AttributeErrors
    def apply(self, ignore_readonly=False):
        original_attrs = {}
        for name, value in self.__dict__['modified_attrs'].items():
            original_attrs[name] = getattr(self.__dict__['obj'], name, None)
            try:
                setattr(self.__dict__['obj'], name, value)
            except AttributeError, e:
                log.error('%s: %s=%s', e, name, value)
                if not ignore_readonly:
                    raise

        # properties could alter the effective value of what we set
        # so we need to read back the actual values from the object
        updated = {}
        for k in self.__dict__['modified_attrs'].keys():
            new_value = getattr(self.__dict__['obj'], k)
            if new_value != original_attrs[k]:
                updated[k] = getattr(self.__dict__['obj'], k)
        # we emit modification events only for objects
        # that have been already added to a container (ON-412)
        if updated and self.__dict__['obj'].__parent__:
            handle(self.__dict__['obj'], ModelModifiedEvent(original_attrs, updated))
Пример #18
0
 def render_delete(self, request):
     name = unicode(parse_path(request.path)[-1])
     existing_object = self.context.__parent__[name]
     if existing_object:
         log.debug('Deleting %s', self.context)
         # are we deleting a container?
         if IStorageContainer.providedBy(self.context):
             # check children
             children = [child for child in self.context.listcontent() if
                         IDataObject.providedBy(child) or
                         IStorageContainer.providedBy(child)]
             if len(children) > 0:
                 raise BadRequest('Attempt to delete a non-empty container')
         else:
             # XXX: Alternative authentication methods!
             credentials = request.getHeader('X-Auth-Token')
             storemgr = getAdapter(self.context, IDataStoreFactory).create()
             storemgr.delete(credentials)
         del self.context.__parent__[name]
         handle(self.context, ModelDeletedEvent(self.context.__parent__))
     else:
         raise NotFound
Пример #19
0
def main():
    gsm.registerHandler(docCreated)
    gsm.registerHandler(docCreated2)

    documents = (('doc1',
                  Document('a document one',
                           'Всем привет. Буквально пару слов обо мне.')),
                 ('doc2',
                  Document(
                      'a document two',
                      'Сейчас я переехал в Германию и работаю в InnoGames.')),
                 ('doc3',
                  Document('a document three',
                           'И сегодня мы поговорим с вами.')))
    # create documents
    for _, d in documents:
        sleep(0.5)
        handle(DocumentCreated(d))

    print('attributes of created documents:')
    for n, d in documents:
        print('Document {!r}'.format(n))
        print_attrs(d)
        print()
Пример #20
0
 def _callFUT(self, *args, **kw):
     from zope.component import handle
     return handle(*args, **kw)
Пример #21
0
    def _sync_vms_transact(self, remote_vms):
        local_vms = [i for i in self.context.listcontent() if IVirtualCompute.providedBy(i)]

        remote_uuids = set(i['uuid'] for i in remote_vms)
        local_uuids = set(i.__name__ for i in local_vms)

        root = db.get_root()['oms_root']
        machines = root['machines']

        for vm_uuid in remote_uuids.difference(local_uuids):
            remote_vm = [rvm for rvm in remote_vms if rvm['uuid'] == vm_uuid][0]

            existing_machine = follow_symlinks(machines['by-name'][remote_vm['name']])
            if existing_machine:
                # XXX: this VM is a nested VM, for now let's hack it this way
                new_compute = Symlink(existing_machine.__name__, existing_machine)
                self.context._add(new_compute)
            else:
                log.msg('Adding virtual compute %s...' % vm_uuid,
                        system='v12n-sync', logLevel=logging.WARNING)
                new_compute = Compute(unicode(remote_vm['name']), unicode(remote_vm['state']))
                new_compute.__name__ = vm_uuid
                new_compute.template = unicode(remote_vm['template'])
                alsoProvides(new_compute, IVirtualCompute)
                alsoProvides(new_compute, IDeployed)

                # for now let's force new synced computes to not have salt installed
                # XXX: not sure if removing a parent interface will remove the child also
                noLongerProvides(new_compute, IManageable)
                self.context.add(new_compute)

        for vm_uuid in remote_uuids.intersection(local_uuids):
            noLongerProvides(self.context[vm_uuid], IUndeployed)
            alsoProvides(self.context[vm_uuid], IDeployed)

        for vm_uuid in local_uuids.difference(remote_uuids):
            if IDeploying.providedBy(self.context[vm_uuid]):
                log.msg("Don't delete undeployed VM while in IDeploying state", system='v12n')
                continue

            noLongerProvides(self.context[vm_uuid], IDeployed)
            alsoProvides(self.context[vm_uuid], IUndeployed)
            self.context[vm_uuid].state = u'inactive'

            if get_config().getboolean('sync', 'delete_on_sync'):
                log.msg("Deleting compute %s" % vm_uuid, system='v12n-sync', logLevel=logging.WARNING)
                compute = self.context[vm_uuid]
                del self.context[vm_uuid]
                handle(compute, ModelDeletedEvent(self.context))

        # TODO: eliminate cross-import between compute and v12ncontainer
        from opennode.knot.backend.compute import ICompute
        from opennode.knot.backend.syncaction import SyncAction

        # sync each vm
        for compute in self.context.listcontent():
            if not IVirtualCompute.providedBy(compute):
                continue

            log.msg('Attempting to sync %s' % compute, system='sync-vms')
            if not ICompute.providedBy(compute.__parent__.__parent__):
                log.msg('Inconsistent data: %s, Compute is expected. Attempting to fix %s'
                        % (compute.__parent__.__parent__, compute),
                        system='sync-vms', logLevel=logging.WARNING)

                compute.__parent__ = self.context

                log.msg('Fixing %s %s' % (compute,
                                          'successful!'
                                          if ICompute.providedBy(compute.__parent__.__parent__)
                                          else 'failed!'),
                        system='sync-vms', logLevel=logging.WARNING)

                if not ICompute.providedBy(compute.__parent__.__parent__):
                    return

            action = SyncAction(compute)

            matching = [rvm for rvm in remote_vms if rvm['uuid'] == compute.__name__]

            if not matching:
                continue

            remote_vm = matching[0]

            # todo delegate all this into the action itself
            default_console = action._default_console()
            action._sync_consoles()
            action.sync_owner_transact(remote_vm)
            action.sync_vm(remote_vm)
            action.create_default_console(default_console)
Пример #22
0
 def handle(self, event):
     factory = event.element.factory
     if factory:
         factory._handle(event)
     else:
         component.handle(event)
Пример #23
0
 def _callFUT(self, *args, **kw):
     from zope.component import handle
     return handle(*args, **kw)
Пример #24
0
 def _after_handler(self, new_item):
     if self.properties('reset-tool-after-create', False):
         self.action_group.get_action('toolbox-pointer').activate()
     component.handle(DiagramItemCreateEvent(new_item))
Пример #25
0
 def handle(self, event):
     factory = event.element.factory
     if factory:
         factory._handle(event)
     else:
         component.handle(event)
Пример #26
0
 def _after_handler(self, new_item):
     if self.properties('reset-tool-after-create', False):
         self.action_group.get_action('toolbox-pointer').activate()
     component.handle(DiagramItemCreateEvent(new_item))
Пример #27
0
def redispatch(event):
    handle(event.obj, event)
Пример #28
0
def redispatch(event):
    handle(event.context, event)
Пример #29
0
def setup_environ(test=False):
    grok_all()
    handle(BeforeApplicationInitalizedEvent(test=test))
    handle(ApplicationInitalizedEvent(test=test))
Пример #30
0
 def _handle(self, event):
     """
     Handle events coming from elements.
     """
     # Invoke default handler, so properties get updated.
     component.handle(event)
Пример #31
0
def redispatch(event):
    handle(event.context, event)