Beispiel #1
0
 def getTemplate(self, resultFormat):
     if resultFormat in self.service.templates:
         return self.service.getTemplate(resultFormat)
     return common.doctypedStan(T.html[
         T.head(render=T.directive("commonhead"))[T.title(
             render=T.directive("meta"))['title'], ],
         T.body(render=T.directive("withsidebar"))[
             T.h1(render=T.directive("meta"))['title'],
             T.div(class_="result", data=T.directive("result"))[T.invisible(
                 render=T.directive(resultFormat))]]])
Beispiel #2
0
class Tests(rend.Page):
    child_foo = FooPage()
    child_stream = StreamerPage()
    child_streamcrash = StreamerCrashPage()
    child_rendercrash = RenderCrashPage()
    child_badgateway = BadGatewayPage()
    child_block = Block()
    child_exit = ExitPage()
    child_clearservice = ServiceUnloadPage()
    child_delay = Delay()
    docFactory = common.doctypedStan(
        T.html[T.head[T.title["Wrong way"], ],
               T.body[T.p["There is nothing here.  Trust me."]]])
Beispiel #3
0
class RenderCrashPage(rend.Page):
    """A page that crashes during render.
	"""
    def render_crash(self, ctx, data):
        try:
            raise Exception("Wanton crash")
        except:
            import traceback
            traceback.print_exc()
            raise

    docFactory = common.doctypedStan(
        T.html[T.head[T.title["A page"], ], T.body[T.p(
            render=T.directive("crash"))["You should not see this"]]])
Beispiel #4
0
class RDInfoRenderer(grend.CustomTemplateMixin, grend.ServiceBasedPage):
    """A renderer for displaying various properties about a resource descriptor.
	
	This renderer could really be attached to any service since
	it does not call it, but it usually lives on //services/overview.

	By virtue of builtin vanity, you can reach the rdinfo renderer
	at /browse, and thus you can access /browse/foo/q to view the RD infos.
	This is the form used by table registrations.
	"""
    name = "rdinfo"
    customTemplate = svcs.loadSystemTemplate("rdlist.html")

    def data_publishedRDs(self, ctx, data):
        td = base.caches.getRD("//services").getById("resources")
        with base.getTableConn() as conn:
            table = rsc.TableForDef(td, connection=conn)
            try:
                return [
                    row["sourceRD"] for row in table.iterQuery(
                        [td.getColumnByName("sourceRD")],
                        "",
                        distinct=True,
                        limits=("ORDER BY sourceRD", {}))
                ]
            finally:
                table.close()

    def locateChild(self, ctx, segments):
        rdId = "/".join(segments)
        if not rdId:
            raise svcs.WebRedirect("browse")
        clientRD = base.caches.getRD(rdId)
        return RDInfoPage(ctx, clientRD), ()

    defaultDocFactory = common.doctypedStan(T.html[
        T.head[T.title["Missing Template"]], T.
        body[T.
             p["The RD list is only available with an rdlist.html template"]]])
Beispiel #5
0
class LogoutRenderer(MetaRenderer):
    """logs users out.

	With a valid authorization header, this emits a 401 unauthorized,
	without one, it displays a logout page.
	"""
    name = "logout"

    openRenderer = True

    def renderHTTP(self, ctx):
        request = inevow.IRequest(ctx)
        if creds.hasCredentials(request.getUser(), request.getPassword(),
                                None):
            # valid credentials: Ask again to make the browser discard them
            raise svcs.Authenticate()
        else:
            return MetaRenderer.renderHTTP(self, ctx)

    defaultDocFactory = common.doctypedStan(
        T.html[T.head[T.title["Logged out"]], T.body[T.h1["Logged out"], T.p[
            "Your browser no longer has valid credentials for this site."
            "  Close this window or continue at the ",
            T.a(href=base.makeAbsoluteURL("/"))["root page"], "."]]])
Beispiel #6
0
class FooPage(rend.Page):
    """is the most basic page conceivable.
	"""
    docFactory = common.doctypedStan(
        T.html[T.head[T.title["A page"], ],
               T.body[T.p["If you see this, you had better know why."]]])
Beispiel #7
0
class AdminRenderer(formal.ResourceMixin, grend.CustomTemplateMixin,
                    grend.ServiceBasedPage):
    """A renderer allowing to block and/or reload services.

	This renderer could really be attached to any service since
	it does not call it, but it usually lives on //services/overview.  
	It will always require authentication.

	It takes the id of the RD to administer from the path segments
	following the renderer name.

	By virtue of builtin vanity, you can reach the admin renderer
	at /seffe, and thus you can access /seffe/foo/q to administer
	the foo/q RD.
	"""
    name = "admin"
    customTemplate = svcs.loadSystemTemplate("admin.html")
    clientRD = None
    # set below when RD loading failed.
    reloadExc = None
    reloadTB = None

    def form_setDowntime(self, ctx):
        form = formal.Form()
        form.addField(
            "scheduled",
            formal.String(),
            label="Schedule downtime for",
            description="Note that this is purely informative.  The server"
            " will not take down the services at this point in time."
            " Leave empty to cancel.  This will also be cleared on a"
            " reload.")
        form.addAction(self.setDowntime, label="Ok")
        form.data = {
            "scheduled": base.getMetaText(self.clientRD, "_scheduledDowntime")
        }
        return form

    def setDowntime(self, ctx, form, data):
        scheduleFor = data.get("scheduled")
        if scheduleFor is None:
            self.clientRD.delMeta("_scheduledDowntime")
        else:
            try:
                stc.parseISODT(scheduleFor)  # check syntax
                self.clientRD.setMeta("_scheduledDowntime", scheduleFor)
            except stc.STCLiteralError:  # bad date syntax
                raise base.ui.logOldExc(
                    formal.FieldError("Doesn't look like ISO", "scheduleFor"))

    def form_adminOps(self, ctx):
        form = formal.Form()
        if hasattr(self.clientRD, "currently_blocked"):
            label = "Unblock"
        else:
            label = "Block"
        form.addAction(self.toggleBlock, label=label, name="block")
        form.addAction(self.reloadRD, label="Reload RD", name="submit")
        return form

    def toggleBlock(self, ctx, form, data):
        if hasattr(self.clientRD, "currently_blocked"):
            delattr(self.clientRD, "currently_blocked")
        else:
            self.clientRD.currently_blocked = True

    def reloadRD(self, ctx, form, data):
        # XXX TODO: load the supposedly changed RD here and raise errors before
        # booting out the old stuff.
        base.caches.clearForName(self.clientRD.sourceId)

    def data_blockstatus(self, ctx, data):
        if hasattr(self.clientRD, "currently_blocked"):
            return "blocked"
        return "not blocked"

    def data_services(self, ctx, data):
        """returns a sequence of service items belonging to clientRD, sorted
		by id.
		"""
        return sorted(self.clientRD.services)

    def render_svclink(self, ctx, data):
        """renders a link to a service info with a service title.
		
		data must be an item returned from data_services.
		"""
        return ctx.tag(href=data.getURL("info"))[base.getMetaText(
            data, "title")]

    def render_rdId(self, ctx, data):
        return ctx.tag[self.clientRD.sourceId]

    def render_ifexc(self, ctx, data):
        """render children if there was an exception during RD load.
		"""
        if self.reloadExc is None:
            return ""
        else:
            return ctx.tag

    def render_exc(self, ctx, data):
        return ctx.tag[repr(self.reloadExc)]

    def render_traceback(self, ctx, data):
        return ctx.tag[self.reloadTB]

    def renderHTTP(self, ctx):
        # naked renderer means admin services itself
        if self.clientRD is None:
            self.clientRD = base.caches.getRD("__system__/services")
        return common.runAuthenticated(ctx, "admin",
                                       super(AdminRenderer, self).renderHTTP,
                                       ctx)

    def _extractDamageInfo(self):
        """called when reload of RD failed; leaves exc. info in some attributes.
		"""
        type, value = sys.exc_info()[:2]
        self.reloadExc = value
        self.reloadTB = traceback.format_exc()

    # the locateChild here is actually the constructor, as it were --
    # each request gets a new AdminRender by web.root
    def locateChild(self, ctx, segments):
        rdId = "/".join(segments)
        try:
            self.clientRD = base.caches.getRD(rdId)
            if hasattr(self.clientRD, "getRealRD"):
                self.clientRD = self.clientRD.getRealRD()

            self.metaCarrier = self.clientRD
            self.macroPackage = self.clientRD
        except base.RDNotFound:
            raise base.ui.logOldExc(
                svcs.UnknownURI("No such resource descriptor: %s" % rdId))
        except Exception:  # RD is botched.  Clear cache and give an error
            base.caches.clearForName(rdId)
            self._extractDamageInfo()
        return self, ()

    defaultDocFactory = common.doctypedStan(
        T.html[T.head[T.title["Missing Template"]], T.body[T.p[
            "Admin services are only available with a admin.html template"]]])
Beispiel #8
0
class RDInfoPage(grend.CustomTemplateMixin, grend.ResourceBasedPage):
    """A page giving infos about an RD.

	This is not a renderer but a helper for RDInfoRenderer.
	"""
    customTemplate = svcs.loadSystemTemplate("rdinfo.html")

    def data_services(self, ctx, data):
        return sorted(self.rd.services,
                      key=lambda s: base.getMetaText(s, "title", default=s.id))

    def data_tables(self, ctx, data):
        return sorted(
            (t for t in self.rd.tables if t.onDisk and not t.temporary),
            key=lambda t: t.id)

    def data_clientRdId(self, ctx, data):
        return self.rd.sourceId

    def _getDescriptionHTML(self, descItem):
        """returns stan for the "description" of a service or a table.

		The RD's description is not picked up.
		"""
        iDesc = descItem.getMeta("description", propagate=False)
        if iDesc is None:
            return ""
        else:
            return T.div(class_="lidescription")[T.xml(
                iDesc.getContent("blockhtml", macroPackage=descItem))]

    def render_rdsvc(self, ctx, service):
        return ctx.tag[T.a(
            href=service.getURL("info")
        )[base.getMetaText(service, "title", default=service.id)],
                       self._getDescriptionHTML(service)]

    def render_rdtable(self, ctx, tableDef):
        qName = tableDef.getQName()

        adqlNote = ""
        if tableDef.adql:
            adqlNote = T.span(class_="adqlnote")[" ", E.ndash,
                                                 " queriable through ",
                                                 T.a(href="/tap")["TAP"],
                                                 " and ",
                                                 T.a(href="/adql")["ADQL"],
                                                 " "]

        return ctx.tag[T.a(href="/tableinfo/%s" % qName)[qName], adqlNote,
                       self._getDescriptionHTML(tableDef)]

    @classmethod
    def makePageTitle(cls, rd):
        """returns a suitable title for the rd info page.

		This is a class method to allow other renderers to generate
		titles for link anchors.
		"""
        return "Information on resource '%s'" % base.getMetaText(
            rd, "title", default="%s" % rd.sourceId)

    def render_title(self, ctx, data):
        return ctx.tag[self.makePageTitle(self.rd)]

    defaultDocFactory = common.doctypedStan(T.html[
        T.head[T.title["Missing Template"]], T.
        body[T.p["RD infos are only available with an rdinfo.html template"]]])
Beispiel #9
0
class ServiceInfoRenderer(MetaRenderer, utils.IdManagerMixin):
    """A renderer showing all kinds of metadata on a service.

	This renderer produces the default referenceURL page.  To change its
	appearance, override the serviceinfo.html template.
	"""
    name = "info"

    customTemplate = svcs.loadSystemTemplate("serviceinfo.html")

    def __init__(self, *args, **kwargs):
        grend.ServiceBasedPage.__init__(self, *args, **kwargs)
        self.describingRD = self.service.rd
        self.footnotes = set()

    def render_title(self, ctx, data):
        return ctx.tag["Information on Service '%s'" %
                       base.getMetaText(self.service, "title")]

    def render_notebubble(self, ctx, data):
        if not data["note"]:
            return ""
        id = data["note"].tag
        self.footnotes.add(data["note"])
        return ctx.tag(href="#note-%s" % id)["Note %s" % id]

    def render_footnotes(self, ctx, data):
        """renders the footnotes as a definition list.
		"""
        return T.dl(class_="footnotes")[[
            T.xml(note.getContent(targetFormat="html"))
            for note in sorted(self.footnotes, key=lambda n: n.tag)
        ]]

    def data_internalpath(self, ctx, data):
        return "%s/%s" % (self.service.rd.sourceId, self.service.id)

    def data_inputFields(self, ctx, data):
        res = [
            f.asInfoDict() for f in self.service.getInputKeysFor("info") +
            self.service.serviceKeys
        ]
        res.sort(key=lambda val: val["name"].lower())
        return res

    def data_htmlOutputFields(self, ctx, data):
        res = [f.asInfoDict() for f in self.service.getCurOutputFields()]
        res.sort(key=lambda val: val["name"].lower())
        return res

    def data_votableOutputFields(self, ctx, data):
        queryMeta = svcs.QueryMeta({"_FORMAT": "VOTable", "_VERB": 3})
        res = [
            f.asInfoDict() for f in self.service.getCurOutputFields(queryMeta)
        ]
        res.sort(key=lambda val: val["verbLevel"])
        return res

    def data_rendAvail(self, ctx, data):
        return [{
            "rendName": rend,
            "rendExpl": RendExplainer.explain(rend, self.service)
        } for rend in self.service.allowed]

    def data_publications(self, ctx, data):
        res = [{
            "sets": ",".join(p.sets),
            "render": p.render
        } for p in self.service.publications if p.sets]
        return sorted(res, key=lambda v: v["render"])

    def data_browserURL(self, ctx, data):
        return self.service.getBrowserURL()

    def data_service(self, ctx, data):
        return self.service

    defaultDocFactory = common.doctypedStan(
        T.html[T.head[T.title["Missing Template"]], T.body[
            T.p["Infos are only available with a serviceinfo.html template"]]])
Beispiel #10
0
        if self.describingRD.getMeta(metaName, propagate=False):
            return lambda ctx, data: ctx.tag
        else:
            return lambda ctx, data: ""

    def data_tableDef(self, ctx, data):
        return self.table

    def locateChild(self, ctx, segments):
        if len(segments) != 1:
            return None, ()
        self._retrieveTableDef(segments[0])
        return self, ()

    defaultDocFactory = common.doctypedStan(T.html[
        T.head[T.title["Missing Template"]], T.
        body[T.p["Infos are only available with a tableinfo.html template"]]])


class TableNoteRenderer(MetaRenderer):
    """A renderer for displaying table notes.

	It takes a schema-qualified table name and a note tag in the segments.

	This does not use the underlying service, so it could and will run on
	any service.  However, you really should run it on __system__/dc_tables/show,
	and there's a built-in vanity name tablenote for this.
	"""
    name = "tablenote"

    def renderHTTP(self, ctx):