Exemplo n.º 1
0
 async def writeReply(self, response: Response, proc: Processor) -> None:
     response.write('<?xml version="1.0" encoding="utf-8"?>')
     # Note: Using an "xml:base" attribute here and relative URLs in the rest
     #       of the feed works fine in Akregator (KDE4 version), but fails in
     #       Outlook 2007. Therefore we should only use absolute URLs.
     response.writeXML(
         atom.feed(xmlns='http://www.w3.org/2005/Atom', )[self.presentFeed(
             proc, rootURL)])
Exemplo n.º 2
0
    async def writeReply(self, response: Response, proc: Processor) -> None:
        matches = proc.matches
        subjectIdName = proc.args.subject + 'id'

        response.writeXML(
            xml.matches[(xml.tag(**{
                subjectIdName: recordId,
                'key': key,
                'value': value,
            }) for recordId, key, value in matches)])
Exemplo n.º 3
0
 async def respond(self, response: Response) -> None:
     self.__page.writeHTTPHeaders(response)
     # TODO: This is copy-pasted from UIPage.
     #       I'm not sure yet where the proper location would be;
     #       if it is copy-pasted a third time it might be clearer.
     proc = self.__proc
     presentationArgs = dict(
         proc=proc,
         styleURL=proc.req.relativeRoot + styleRoot.relativeURL,
     )
     response.writeXML(self.__widget.present(**presentationArgs))
Exemplo n.º 4
0
 def writeHTML(self, response: Response, proc: ProcT) -> None:
     req = proc.req
     ccURL = req.relativeRoot
     presentationArgs = dict(
         proc=proc,
         ccURL=ccURL,
         styleURL=ccURL + styleRoot.relativeURL,
     )
     response.write('<!DOCTYPE html>\n')
     response.writeXML(
         xhtml.html(lang='en')[xhtml.head[self.presentHeadParts(
             **presentationArgs)], xhtml.body[self.__presentBodyParts(
                 req, response, **presentationArgs)], ])
Exemplo n.º 5
0
 async def writeReply(self, response: Response, proc: Processor) -> None:
     response.writeXML(
         xml.factory(
             name = proc.project.name,
             url = rootURL,
             version = VERSION,
             boottime = formatTimeAttr(getBootTime()),
             timezone = proc.project.timezone,
             )[
             ( xml.table(name = db.name, count = len(db))
               for db in proc.databases ),
             ]
         )
Exemplo n.º 6
0
    async def writeReply(self, response: Response, proc: Processor) -> None:
        args: GetTaskDefParams_GET.Arguments = proc.args
        requestedParams = args.param

        def externalizeParams(taskParams: Mapping[str, str]) -> XMLContent:
            for param in requestedParams or taskParams:
                value = taskParams.get(param)
                if value is not None:
                    yield xml.param(name=param, value=value)

        response.writeXML(
            xml.taskdefs[(xml.taskdef(name=taskId)[externalizeParams(
                taskDef.getParameters())]
                          for taskId, taskDef in proc.taskDefDB.items())])
Exemplo n.º 7
0
async def renderAsync(page: FabResource, request: TwistedRequest) -> None:
    req: Request = Request(request)
    authenticator = page.authenticator
    response = Response(request,
                        authenticator.project.frameAncestors,
                        req.userAgent)

    try:
        try:
            user: User = await authenticator.authenticate(req)
        except LoginFailed as ex:
            if req.getSubPath() is None:
                responder = authenticator.askForAuthentication(
                    req, ex.args[0] if ex.args else None
                    )
            else:
                # Widget requests should just fail immediately instead of
                # asking for authentication.
                responder = _unauthorizedResponder(ex)
        except Unauthorized as ex:
            responder = _unauthorizedResponder(ex)
        else:
            responder = await _parseAndProcess(page, req, user)
    except Redirect as ex:
        responder = Redirector(ex.url)
    except InternalError as ex:
        logging.error(
            'Internal error processing %s: %s', page.name, str(ex)
            )
        responder = UIResponder(
            InternalErrorPage[PageProcessor](str(ex)),
            PageProcessor(page, req, FabResource.Arguments(), UnknownUser())
            )

    await _present(responder, response)
Exemplo n.º 8
0
 async def respond(self, response: Response) -> None:
     page = self.page
     proc = self.proc
     response.setContentType('text/x-csv; charset=UTF-8')
     response.setFileName(page.getFileName(proc))
     sepChar = proc.args.sep.value
     for row in page.iterRows(proc):
         response.write(sepChar.join(row) + '\r\n')
Exemplo n.º 9
0
async def _present(responder: Responder, response: Response) -> None:
    """Presentation step: write a response based on the processing results."""
    if _timeRender:
        start = time()
    if _profileRender:
        profile = Profile()
        # Note: This will only profile the execution until the first
        #       'await' in the responder. However, a lot of pages do
        #       their whole presentation in one go, so in many cases
        #       this is good enough.
        try:
            await profile.runcall(responder.respond, response)
        except NotModified:
            pass
        profile.dump_stats('request.prof')
    else:
        try:
            await responder.respond(response)
        except NotModified:
            pass
    if _timeRender:
        end = time()
        print('Responding took %1.3f seconds' % (end - start))
    response.finish()
Exemplo n.º 10
0
 async def writeReply(self, response: Response, proc: Processor) -> None:
     jobs = proc.jobs
     response.write('<jobrefs>')
     for chunk in chop(jobs, 1000):
         # Measurements have shown that a single write with a big XML
         # sequence is much faster than many small writes.
         response.writeXML(xml.jobref(jobid=job.getId()) for job in chunk)
         # Return control to reactor.
         await response.returnToReactor()
     response.write('</jobrefs>')
Exemplo n.º 11
0
 async def respond(self, response: Response) -> None:
     response.setStatus(500, 'Unexpected exception processing request')
     self.proc.processingError = self.__exception
     await super().respond(response)
Exemplo n.º 12
0
 async def writeReply(self, response: Response, proc: Processor) -> None:
     response.writeXML(xml.response[proc.createResponse()])
Exemplo n.º 13
0
 async def respond(self, response: Response) -> None:
     page = self.page
     proc = self.proc
     response.setContentType(page.getContentType(proc))
     await page.writeReply(response, proc)
Exemplo n.º 14
0
 async def respond(self, response: Response) -> None:
     response.setStatus(500, 'Unexpected exception processing request')
     response.setContentType('text/plain')
     response.write('Unexpected exception processing request.\n'
                    'Details were written to the server log.\n')
Exemplo n.º 15
0
 async def respond(self, response: Response) -> None:
     response.setStatus(401, self.__message)
     response.setHeader('WWW-Authenticate', f'Basic realm="{self.__realm}"')
Exemplo n.º 16
0
 async def writeReply(self, response: Response, proc: Processor) -> None:
     response.writeXML(xml.ok)
Exemplo n.º 17
0
    async def writeReply(self, response: Response, proc: Processor) -> None:
        taskprio = proc.project['taskprio']

        def taskToXML(task: Task) -> XML:
            run = task.getLatestRun()
            return xml.task(
                name = task.getName(),
                priority = task.getPriority() if taskprio else None,
                waiting = run.isWaiting(),
                running = run.isRunning(),
                done = run.isDone(),
                cancelled = run.isCancelled(),
                result = task.result,
                alert = task.getAlert(),
                summary = run.getSummary(),
                report = task.getURL(),
                starttime = formatTimeAttr(task.startTime),
                duration = task.getDuration(),
                runner = run.getTaskRunnerId(),
                )[
                ( xml.param(name = name, value = value)
                  for name, value in task.getVisibleParameters().items() )
                ]

        def productToXML(product: Product, listProducers: bool) -> XML:
            prodType = product.getType()
            return xml.product(
                name = product.getName(),
                type = prodType,
                available = product.isAvailable(),
                blocked = product.isBlocked(),
                local = product.isLocal(),
                combined = product.isCombined(),
                localat = product.getLocalAt(),
                locator = None if prodType is ProductType.TOKEN
                    else product.getLocator(),
                )[
                ( xml.producer(
                    name = name,
                    locator = None if prodType is ProductType.TOKEN else locator
                    )
                    for name, locator in product.getProducers()
                    ) if listProducers else None
                ]

        job = proc.job
        job.updateSummaries(list(proc.resourceDB.iterTaskRunners()))
        comment = job.comment
        tasks = job.getTaskSequence()
        response.writeXML(
            xml.job(
                jobid = job.getId(),
                target = job.getTarget(),
                createtime = formatTimeAttr(job.getCreateTime()),
                configid = job.configId,
                owner = job.owner,
                scheduledby = job.getScheduledBy(),
                )
            [
            xml.comment[ comment ] if comment else None,
            ( taskToXML(task) for task in tasks ),
            xml.inputs[
                ( productToXML(prod, False) for prod in job.getInputs() )
                ],
            xml.outputs[
                ( productToXML(prod, True) for prod in job.getProduced() )
                ],
            ])
Exemplo n.º 18
0
 async def respond(self, response: Response) -> None:
     response.sendRedirect(self.__url)
Exemplo n.º 19
0
 async def respond(self, response: Response) -> None:
     export = self.__export
     fmt = self.__format
     response.setContentType(fmt.mediaType)
     if export:
         response.setFileName(f'{self.__fileName}.{fmt.ext}')
     else:
         response.allowEmbedding()
     data = self.__builder.build(export).data
     response.setETag(createETag(data) + b'-dot')
     try:
         rendered = await _renderGraph(data, fmt)
     except Exception as ex:
         response.setStatus(500, 'Graph rendering failed')
         response.setContentType('text/plain')
         response.write(f'Graph rendering failed: {ex}\n')
     else:
         response.write(rendered)
Exemplo n.º 20
0
 async def respond(self, response: Response) -> None:
     response.setStatus(500)
     self.proc.error = self.error
     await super().respond(response)
Exemplo n.º 21
0
    async def writeReply(self, response: Response, proc: Processor) -> None:

        def iterChangedBy(resource: ResourceBase) -> Iterator[XML]:
            user = resource.getChangedUser()
            if user:
                # Currently 'user' is always 'None' for custom resources
                yield xml.changedby(
                    name = user,
                    time = formatTimeAttr(resource.getChangedTime()),
                    )

        def iterReservedBy(resource: ResourceBase) -> Iterator[XML]:
            if isinstance(resource, TaskRunner):
                # Resource is a Task Runner.
                runner = resource
                run = runner.getRun()
                if run:
                    yield xml.reservedby[
                        xml.taskref(
                            taskname = run.getName(),
                            jobid = run.getJob().getId(),
                            )
                        ]
            else:
                # Resource is of a custom type.
                if resource.isReserved():
                    yield xml.reservedby[
                        xml.userref(
                            userid = cast(str, resource['reserved'])
                            )
                        ]

        def iterResourceContent(resource: ResourceBase) -> Iterator[XML]:
            # Resource type independent information
            for cap in resource.capabilities:
                yield xml.capability(name = cap)
            yield from iterChangedBy(resource)
            yield from iterReservedBy(resource)
            if isinstance(resource, TaskRunner):
                # Include Task Runner specific infomation.
                yield xml.taskrunner(
                    connectionstatus = resource.getConnectionStatus(),
                    version = cast(str, resource['runnerVersion']),
                    exitonidle = resource.shouldExit(),
                    lastsync = cast(Optional[int], resource['lastSync']),
                    )
            else:
                # Include information on custom resource type.
                yield xml.custom(
                    description = resource.description
                    )

        response.writeXML(xml.resources[(
            xml.resource(
                # Resource type independent information
                type = resource.typeName,
                name = resource.getId(),
                suspended = resource.isSuspended(),
                locator = resource.getParameter('locator')
                )[iterResourceContent(resource)]
            for resource in proc.resources
            )])
Exemplo n.º 22
0
 async def writeReply(self, response: Response, proc: Processor) -> None:
     response.writeXML(xml.abortedtasks[(
         xml.taskref(jobid=jobId, taskname=taskName)
         for jobId, taskNames in proc.abortedTasks.items()
         for taskName in taskNames)])
Exemplo n.º 23
0
 async def respond(self, response: Response) -> None:
     response.setStatus(self.__status, self.__message)
     response.setContentType('text/plain')
     response.write(self.__message + '\n')