Esempio n. 1
0
def plugins(request):
    """
    TODO: This is blocking,
    We could do that using green threads or multithreads...
    Or even, we could do those requests on client side
    """
    Service = namedtuple('Service', [
        'name',
        'status',
        'pid',
        'start_url',
        'stop_url',
        'status_url',
    ])

    plugins = Plugins.objects.filter(plugin_enabled=True)
    host = get_base_url(request)
    for plugin in plugins:
        url = "%s/plugins/%s/_s/status" % (host, plugin.plugin_name)
        try:
            opener = urllib2.build_opener()
            opener.addheaders = [
                ('Cookie',
                 'sessionid=%s' % request.COOKIES.get("sessionid", ''))
            ]
            response = opener.open(url, None, 1).read()
            json = simplejson.loads(response)
        except Exception, e:
            log.warn(
                _("Couldn't retrieve %(url)s: %(error)s") % {
                    'url': url,
                    'error': e,
                })
            continue
        plugin.service = Service(
            name=plugin.plugin_name,
            status=json['status'],
            pid=json.get("pid", None),
            start_url="/plugins/%s/_s/start" % (plugin.plugin_name, ),
            stop_url="/plugins/%s/_s/stop" % (plugin.plugin_name, ),
            status_url="/plugins/%s/_s/status" % (plugin.plugin_name, ),
        )
Esempio n. 2
0
def plugins(request):
    """
    TODO: This is blocking,
    We could do that using green threads or multithreads...
    Or even, we could do those requests on client side
    """
    Service = namedtuple('Service', [
        'name',
        'status',
        'pid',
        'start_url',
        'stop_url',
        'status_url',
        ])

    plugins = Plugins.objects.filter(plugin_enabled=True)
    host = get_base_url(request)
    for plugin in plugins:
        url = "%s/plugins/%s/_s/status" % (
            host,
            plugin.plugin_name)
        try:
            opener = urllib2.build_opener()
            opener.addheaders = [('Cookie', 'sessionid=%s' % request.COOKIES.get("sessionid", ''))]
            response = opener.open(url, None, 1).read()
            json = simplejson.loads(response)
        except Exception, e:
            log.warn(_("Couldn't retrieve %(url)s: %(error)s") % {
                'url': url,
                'error': e,
                })
            continue
        plugin.service = Service(
            name=plugin.plugin_name,
            status=json['status'],
            pid=json.get("pid", None),
            start_url="/plugins/%s/_s/start" % (plugin.plugin_name, ),
            stop_url="/plugins/%s/_s/stop" % (plugin.plugin_name, ),
            status_url="/plugins/%s/_s/status" % (plugin.plugin_name, ),
            )
Esempio n. 3
0
    def generate(self, request=None):
        """
        Tree Menu Auto Generate

        Every app listed at INSTALLED_APPS is scanned
        1st - app_name.forms is imported. All its objects/classes are scanned
            looking for ModelForm classes
        2nd - app_name.nav is imported. TreeNode classes are scanned for
            hard-coded menu entries or overwriting
        3rd - app_name.models is imported. models.Model classes are scanned,
        if a related ModelForm is found several entries are Added to the Menu
                - Objects
                - Add (Model)
                - View (Model)
        """

        self._generated = True
        self._navs.clear()
        tree_roots.clear()
        _childs_of = []
        for app in settings.INSTALLED_APPS:

            # If the app is listed at settings.BLACKLIST_NAV, skip it!
            if app in getattr(settings, 'BLACKLIST_NAV', []):
                continue

            # Thats the root node for the app tree menu
            nav = TreeRoot(app)

            modnav = self._get_module(app, 'nav')
            if hasattr(modnav, 'BLACKLIST'):
                BLACKLIST = modnav.BLACKLIST
            else:
                BLACKLIST = []

            if hasattr(modnav, 'ICON'):
                nav.icon = modnav.ICON

            if hasattr(modnav, 'NAME'):
                nav.name = modnav.NAME
            else:
                nav.name = self.titlecase(app)

            if modnav:
                modname = "%s.nav" % app
                for c in dir(modnav):
                    navc = getattr(modnav, c)
                    try:
                        subclass = issubclass(navc, TreeNode)
                    except TypeError:
                        continue
                    if navc.__module__ == modname and subclass:
                        obj = navc()

                        if obj.skip is True:
                            continue
                        if not obj.append_to:
                            self.register_option(obj, nav, replace=True)
                        else:
                            self._navs[obj.append_to + '.' + obj.gname] = obj

                tree_roots.register(nav)  # We register it to the tree root
                if hasattr(modnav, 'init'):
                    modnav.init(tree_roots, nav)

            else:
                log.debug("App %s has no nav.py module, skipping", app)
                continue

            modmodels = self._get_module(app, 'models')
            if modmodels:

                modname = '%s.models' % app
                for c in dir(modmodels):
                    model = getattr(modmodels, c)
                    try:
                        if not issubclass(model, models.Model) or \
                            model._meta.app_label != app:
                            continue
                    except TypeError:
                        continue

                    if c in BLACKLIST:
                        log.debug("Model %s from app %s blacklisted, skipping",
                            c,
                            app,
                            )
                        continue

                    if not(model.__module__ in (modname,
                                'metanasUI.' + modname) \
                            and model in self._modelforms
                          ):
                        log.debug("Model %s does not have a ModelForm", model)
                        continue

                    if model._admin.deletable is False:
                        navopt = TreeNode(str(model._meta.object_name),
                            name=model._meta.verbose_name,
                            model=c, app_name=app, type='dialog')
                        try:
                            navopt.kwargs = {'app': app, 'model': c, 'oid': \
                                model.objects.order_by("-id")[0].id}
                            navopt.view = 'freeadmin_model_edit'
                        except:
                            navopt.view = 'freeadmin_model_add'
                            navopt.kwargs = {'app': app, 'model': c}

                    else:
                        navopt = TreeNode(str(model._meta.object_name))
                        navopt.name = model._meta.verbose_name_plural
                        navopt.model = c
                        navopt.app_name = app
                        navopt.order_child = False

                    for key in model._admin.nav_extra.keys():
                        navopt.__setattr__(key,
                            model._admin.nav_extra.get(key))
                    if model._admin.icon_model is not None:
                        navopt.icon = model._admin.icon_model

                    if model._admin.menu_child_of is not None:
                        _childs_of.append((navopt, model))
                        reg = True
                    else:
                        reg = self.register_option(navopt, nav)

                    if reg and not navopt.type:

                        qs = model.objects.filter(
                            **model._admin.object_filters).order_by('-id')
                        if qs.count() > 0:
                            if model._admin.object_num > 0:
                                qs = qs[:model._admin.object_num]
                            for e in qs:
                                subopt = TreeNode('Edit')
                                subopt.type = 'editobject'
                                subopt.view = u'freeadmin_model_edit'
                                if model._admin.icon_object is not None:
                                    subopt.icon = model._admin.icon_object
                                subopt.model = c
                                subopt.app_name = app
                                subopt.kwargs = {
                                    'app': app,
                                    'model': c,
                                    'oid': e.id,
                                    }
                                try:
                                    subopt.name = unicode(e)
                                except:
                                    subopt.name = 'Object'
                                navopt.append_child(subopt)

                        # Node to add an instance of model
                        subopt = TreeNode('Add')
                        subopt.name = _(u'Add %s') % model._meta.verbose_name
                        subopt.view = u'freeadmin_model_add'
                        subopt.kwargs = {'app': app, 'model': c}
                        subopt.order = 500
                        subopt.type = 'dialog'
                        if model._admin.icon_add is not None:
                            subopt.icon = model._admin.icon_add
                        subopt.model = c
                        subopt.app_name = app
                        self.register_option(subopt, navopt)

                        # Node to view all instances of model
                        subopt = TreeNode('View')
                        subopt.name = _(u'View %s') % (
                            model._meta.verbose_name_plural,
                            )
                        subopt.view = u'freeadmin_model_datagrid'
                        if model._admin.icon_view is not None:
                            subopt.icon = model._admin.icon_view
                        subopt.model = c
                        subopt.app_name = app
                        subopt.kwargs = {'app': app, 'model': c}
                        subopt.order = 501
                        subopt.type = 'viewmodel'
                        self.register_option(subopt, navopt)

        nav = TreeRoot('display',
            name=_('Display System Processes'),
            action='displayprocs',
            icon='TopIcon')
        tree_roots.register(nav)

        nav = TreeRoot('shell',
            name=_('Shell'),
            icon='TopIcon',
            action='shell')
        tree_roots.register(nav)

        nav = TreeRoot('reboot',
            name=_('Reboot'),
            action='reboot',
            icon='RebootIcon',
            type='scary_dialog',
            view='system_reboot_dialog')
        tree_roots.register(nav)

        nav = TreeRoot('shutdown',
            name=_('Shutdown'),
            icon='ShutdownIcon',
            type='scary_dialog',
            view='system_shutdown_dialog')
        tree_roots.register(nav)

        for opt, model in _childs_of:
            for nav in tree_roots:
                exists = nav.find_gname(model._admin.menu_child_of)
                if exists is not False:
                    exists.append_child(opt)
                    break
            if exists is False:
                log.debug("Could not find %s to attach %r",
                    model._admin.menu_child_of,
                    opt)

        self.replace_navs(tree_roots)

        """
        Plugin nodes
        TODO: It is a blocking operation, we could use green threads
        """
        host = get_base_url(request)

        for plugin in Plugins.objects.filter(plugin_enabled=True):

            try:
                url = "%s/plugins/%s/_s/treemenu" % (host, plugin.plugin_name)
                opener = urllib2.build_opener()
                opener.addheaders = [('Cookie', 'sessionid=%s' % request.COOKIES.get("sessionid", ''))]
                response = opener.open(url, None, 1)
                data = response.read()
                if not data:
                    log.warn(_("Empty data returned from %s") % (url,))
                    continue
            except Exception, e:
                log.warn(_("Couldn't retrieve %(url)s: %(error)s") % {
                    'url': url,
                    'error': e,
                    })
                continue

            try:
                data = simplejson.loads(data)

                nodes = unserialize_tree(data)
                for node in nodes:
                    #We have our TreeNode's, find out where to place them

                    found = False
                    if node.append_to:
                        log.debug("Plugin %s requested to be appended to %s",
                            plugin.plugin_name, node.append_to)
                        places = node.append_to.split('.')
                        places.reverse()
                        for root in tree_roots:
                            find = root.find_place(list(places))
                            if find:
                                find.append_child(node)
                                found = True
                                break
                    else:
                        log.debug("Plugin %s didn't request to be appended anywhere specific",
                            plugin.plugin_name)

                    if not found:
                        node.tree_root = 'main'
                        tree_roots.register(node)

            except Exception, e:
                log.warn(_("An error occurred while unserializing from "
                    "%(url)s: %(error)s") % {'url': url, 'error': e})
                continue
Esempio n. 4
0
    def generate(self, request=None):
        """
        Tree Menu Auto Generate

        Every app listed at INSTALLED_APPS is scanned
        1st - app_name.forms is imported. All its objects/classes are scanned
            looking for ModelForm classes
        2nd - app_name.nav is imported. TreeNode classes are scanned for
            hard-coded menu entries or overwriting
        3rd - app_name.models is imported. models.Model classes are scanned,
        if a related ModelForm is found several entries are Added to the Menu
                - Objects
                - Add (Model)
                - View (Model)
        """

        self._generated = True
        self._navs.clear()
        tree_roots.clear()
        _childs_of = []
        for app in settings.INSTALLED_APPS:

            # If the app is listed at settings.BLACKLIST_NAV, skip it!
            if app in getattr(settings, 'BLACKLIST_NAV', []):
                continue

            # Thats the root node for the app tree menu
            nav = TreeRoot(app)

            modnav = self._get_module(app, 'nav')
            if hasattr(modnav, 'BLACKLIST'):
                BLACKLIST = modnav.BLACKLIST
            else:
                BLACKLIST = []

            if hasattr(modnav, 'ICON'):
                nav.icon = modnav.ICON

            if hasattr(modnav, 'NAME'):
                nav.name = modnav.NAME
            else:
                nav.name = self.titlecase(app)

            if modnav:
                modname = "%s.nav" % app
                for c in dir(modnav):
                    navc = getattr(modnav, c)
                    try:
                        subclass = issubclass(navc, TreeNode)
                    except TypeError:
                        continue
                    if navc.__module__ == modname and subclass:
                        obj = navc()

                        if obj.skip is True:
                            continue
                        if not obj.append_to:
                            self.register_option(obj, nav, replace=True)
                        else:
                            self._navs[obj.append_to + '.' + obj.gname] = obj

                tree_roots.register(nav)  # We register it to the tree root
                if hasattr(modnav, 'init'):
                    modnav.init(tree_roots, nav)

            else:
                log.debug("App %s has no nav.py module, skipping", app)
                continue

            modmodels = self._get_module(app, 'models')
            if modmodels:

                modname = '%s.models' % app
                for c in dir(modmodels):
                    model = getattr(modmodels, c)
                    try:
                        if not issubclass(model, models.Model) or \
                            model._meta.app_label != app:
                            continue
                    except TypeError:
                        continue

                    if c in BLACKLIST:
                        log.debug(
                            "Model %s from app %s blacklisted, skipping",
                            c,
                            app,
                        )
                        continue

                    if not(model.__module__ in (modname,
                                'metanasUI.' + modname) \
                            and model in self._modelforms
                          ):
                        log.debug("Model %s does not have a ModelForm", model)
                        continue

                    if model._admin.deletable is False:
                        navopt = TreeNode(str(model._meta.object_name),
                                          name=model._meta.verbose_name,
                                          model=c,
                                          app_name=app,
                                          type='dialog')
                        try:
                            navopt.kwargs = {'app': app, 'model': c, 'oid': \
                                model.objects.order_by("-id")[0].id}
                            navopt.view = 'freeadmin_model_edit'
                        except:
                            navopt.view = 'freeadmin_model_add'
                            navopt.kwargs = {'app': app, 'model': c}

                    else:
                        navopt = TreeNode(str(model._meta.object_name))
                        navopt.name = model._meta.verbose_name_plural
                        navopt.model = c
                        navopt.app_name = app
                        navopt.order_child = False

                    for key in model._admin.nav_extra.keys():
                        navopt.__setattr__(key,
                                           model._admin.nav_extra.get(key))
                    if model._admin.icon_model is not None:
                        navopt.icon = model._admin.icon_model

                    if model._admin.menu_child_of is not None:
                        _childs_of.append((navopt, model))
                        reg = True
                    else:
                        reg = self.register_option(navopt, nav)

                    if reg and not navopt.type:

                        qs = model.objects.filter(
                            **model._admin.object_filters).order_by('-id')
                        if qs.count() > 0:
                            if model._admin.object_num > 0:
                                qs = qs[:model._admin.object_num]
                            for e in qs:
                                subopt = TreeNode('Edit')
                                subopt.type = 'editobject'
                                subopt.view = u'freeadmin_model_edit'
                                if model._admin.icon_object is not None:
                                    subopt.icon = model._admin.icon_object
                                subopt.model = c
                                subopt.app_name = app
                                subopt.kwargs = {
                                    'app': app,
                                    'model': c,
                                    'oid': e.id,
                                }
                                try:
                                    subopt.name = unicode(e)
                                except:
                                    subopt.name = 'Object'
                                navopt.append_child(subopt)

                        # Node to add an instance of model
                        subopt = TreeNode('Add')
                        subopt.name = _(u'Add %s') % model._meta.verbose_name
                        subopt.view = u'freeadmin_model_add'
                        subopt.kwargs = {'app': app, 'model': c}
                        subopt.order = 500
                        subopt.type = 'dialog'
                        if model._admin.icon_add is not None:
                            subopt.icon = model._admin.icon_add
                        subopt.model = c
                        subopt.app_name = app
                        self.register_option(subopt, navopt)

                        # Node to view all instances of model
                        subopt = TreeNode('View')
                        subopt.name = _(u'View %s') % (
                            model._meta.verbose_name_plural, )
                        subopt.view = u'freeadmin_model_datagrid'
                        if model._admin.icon_view is not None:
                            subopt.icon = model._admin.icon_view
                        subopt.model = c
                        subopt.app_name = app
                        subopt.kwargs = {'app': app, 'model': c}
                        subopt.order = 501
                        subopt.type = 'viewmodel'
                        self.register_option(subopt, navopt)

        nav = TreeRoot('display',
                       name=_('Display System Processes'),
                       action='displayprocs',
                       icon='TopIcon')
        tree_roots.register(nav)

        nav = TreeRoot('shell',
                       name=_('Shell'),
                       icon='TopIcon',
                       action='shell')
        tree_roots.register(nav)

        nav = TreeRoot('reboot',
                       name=_('Reboot'),
                       action='reboot',
                       icon='RebootIcon',
                       type='scary_dialog',
                       view='system_reboot_dialog')
        tree_roots.register(nav)

        nav = TreeRoot('shutdown',
                       name=_('Shutdown'),
                       icon='ShutdownIcon',
                       type='scary_dialog',
                       view='system_shutdown_dialog')
        tree_roots.register(nav)

        for opt, model in _childs_of:
            for nav in tree_roots:
                exists = nav.find_gname(model._admin.menu_child_of)
                if exists is not False:
                    exists.append_child(opt)
                    break
            if exists is False:
                log.debug("Could not find %s to attach %r",
                          model._admin.menu_child_of, opt)

        self.replace_navs(tree_roots)
        """
        Plugin nodes
        TODO: It is a blocking operation, we could use green threads
        """
        host = get_base_url(request)

        for plugin in Plugins.objects.filter(plugin_enabled=True):

            try:
                url = "%s/plugins/%s/_s/treemenu" % (host, plugin.plugin_name)
                opener = urllib2.build_opener()
                opener.addheaders = [
                    ('Cookie',
                     'sessionid=%s' % request.COOKIES.get("sessionid", ''))
                ]
                response = opener.open(url, None, 1)
                data = response.read()
                if not data:
                    log.warn(_("Empty data returned from %s") % (url, ))
                    continue
            except Exception, e:
                log.warn(
                    _("Couldn't retrieve %(url)s: %(error)s") % {
                        'url': url,
                        'error': e,
                    })
                continue

            try:
                data = simplejson.loads(data)

                nodes = unserialize_tree(data)
                for node in nodes:
                    #We have our TreeNode's, find out where to place them

                    found = False
                    if node.append_to:
                        log.debug("Plugin %s requested to be appended to %s",
                                  plugin.plugin_name, node.append_to)
                        places = node.append_to.split('.')
                        places.reverse()
                        for root in tree_roots:
                            find = root.find_place(list(places))
                            if find:
                                find.append_child(node)
                                found = True
                                break
                    else:
                        log.debug(
                            "Plugin %s didn't request to be appended anywhere specific",
                            plugin.plugin_name)

                    if not found:
                        node.tree_root = 'main'
                        tree_roots.register(node)

            except Exception, e:
                log.warn(
                    _("An error occurred while unserializing from "
                      "%(url)s: %(error)s") % {
                          'url': url,
                          'error': e
                      })
                continue