示例#1
0
    def getChild(self, name, request):
        if name == '':
            return self

        td = '.twistd'

        if name[-len(td):] == td:
            username = name[:-len(td)]
            sub = 1
        else:
            username = name
            sub = 0
        try:
            pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
                     = self._pwd.getpwnam(username)
        except KeyError:
            return resource.NoResource()
        if sub:
            twistdsock = os.path.join(pw_dir, self.userSocketName)
            rs = ResourceSubscription('unix',twistdsock)
            self.putChild(name, rs)
            return rs
        else:
            path = os.path.join(pw_dir, self.userDirName)
            if not os.path.exists(path):
                return resource.NoResource()
            return static.File(path)
示例#2
0
 def getChild(self, name, request):
     # Check if it is the greeting url
     if not name and not request.postpath:
         return self
     # Hacks to resove the iframe even when people are dumb
     if len(name) > 10 and name[:6] == "iframe" and name[-5:] == ".html":
         return self.children["iframe.html"]
     # Sessions must have 3 parts, name is already the first. Also, no periods in the loadbalancer
     if len(request.postpath) != 2 or "." in name or not name:
         return resource.NoResource("No such child resource.")
     # Extract session & request type. Discard load balancer
     session, name = request.postpath
     # No periods in the session
     if "." in session or not session:
         return resource.NoResource("No such child resource.")
     # Websockets are a special case
     if name == "websocket":
         return self._websocket
     # Reject invalid methods
     if name not in self._methods:
         return resource.NoResource("No such child resource.")
     # Reject writes to invalid sessions, unless just checking options
     if name in self._writeMethods and session not in self._sessions and request.method != "OPTIONS":
         return resource.NoResource("No such child resource.")
     # Generate session if doesn't exist, unless just checking options
     if session not in self._sessions and request.method != "OPTIONS":
         self._sessions[session] = Stub(self, session)
     # Delegate request to appropriate handler
     return self._methods[name](
         self,
         self._sessions[session] if request.method != "OPTIONS" else None)
示例#3
0
 def _getResourceForRequest(self, request):
     """(Internal) Get the appropriate resource for the given host."""
     hostHeader = request.getHeader(b"host")
     if hostHeader == None:
         return self.default or resource.NoResource()
     else:
         host = hostHeader.lower().split(b":", 1)[0]
     return self.hosts.get(host, self.default) or resource.NoResource(
         "host %s not in vhost map" % repr(host))
示例#4
0
    def getChild(self, path, request):
        try:
            build_request_id = int(path)
        except (TypeError, ValueError):
            return resource.NoResource('Invalid build request ID.')

        if request.postpath and request.postpath[0] == 'build_number':
            return BuildNumberForRequestJsonResource(self.status,
                                                     build_request_id)

        return resource.NoResource('Resource not found.')
示例#5
0
    def getChild(self, name, request):
        metric = self.processor.timer_metrics.get(name, None) or \
                self.processor.plugin_metrics.get(name, None)
        if metric is None:
            return resource.NoResource()

        meth = getattr(metric, "getResource", None)

        if meth is None:
            return resource.NoResource()

        return meth()
示例#6
0
	def getChild (self, name, request):
		if name == "":
			return self

		if name == "run":
			try:
				id = int(request.postpath.pop(0)) - 1  # This is so that the default will be -1 not 0.
				script = self._scripts[id]
			except IndexError:
				return resource.NoResource(message = "Script #%s is not defined" % id)
			else:
				return ProgramRun(id, script)

		else:
			return resource.NoResource()
示例#7
0
 def render(self, request):
     request.startedWriting = 1
     try:
         with file(self.path) as f:
             return cleanHeaders(f.read())
     except Exception as e:
         return resource.NoResource(repr(e)).render(request)
示例#8
0
 def getChild(self, path, request):
     if path == '':
         return self
     filepath = os.path.join(settings.IdentityServerDir(), path)
     if os.path.isfile(filepath):
         return static.File(filepath)
     return resource.NoResource('Not found')
示例#9
0
	def render(self, request):
		"""Render me to a web client.

		Load my file, execute it in a special namespace (with 'request' and
		'__file__' global vars) and finish the request.  Output to the web-page
		will NOT be handled with print - standard output goes to the log - but
		with request.write.
		"""
		request.setHeader("x-powered-by","Twisted/14")
		namespace = {'request': request,
					 '__file__': self.filename,
					 'registry': self.registry}
		try:
			f = open(self.filename,'r')
			buf = f.read()
			f.close()
			mystr = "__tmp_variable = %s" % buf
			dc = DictConfig(excstr=mystr)
			d = dc.__tmp_variable
			return jsonEncode(d)
			# execfile(self.filename, namespace, namespace)
		except IOError as e:
			if e.errno == 2: #file not found
				request.setResponseCode(http.NOT_FOUND)
				request.write(resource.NoResource("File not found.").render(request))
		except:
			io = StringIO.StringIO()
			traceback.print_exc(file=io)
			request.write(html.PRE(io.getvalue()))
示例#10
0
    def render(self, request):
        """
        Render me to a web client.

        Load my file, execute it in a special namespace (with 'request' and
        '__file__' global vars) and finish the request.  Output to the web-page
        will NOT be handled with print - standard output goes to the log - but
        with request.write.
        """
        request.setHeader(b"x-powered-by",
                          networkString("Twisted/%s" % copyright.version))
        namespace = {
            'request': request,
            '__file__': _coerceToFilesystemEncoding("", self.filename),
            'registry': self.registry
        }
        try:
            execfile(self.filename, namespace, namespace)
        except IOError as e:
            if e.errno == 2:  #file not found
                request.setResponseCode(http.NOT_FOUND)
                request.write(
                    resource.NoResource("File not found.").render(request))
        except:
            io = NativeStringIO()
            traceback.print_exc(file=io)
            output = util._PRE(io.getvalue())
            if _PY3:
                output = output.encode("utf8")
            request.write(output)
        request.finish()
        return server.NOT_DONE_YET
示例#11
0
 def getChild(self, path, request):
     if not path:
         return self
     filepath = os.path.join(settings.IdentityServerDir(), strng.to_text(path))
     if os.path.isfile(filepath):
         return static.File(filepath)
     return resource.NoResource('Not found')
示例#12
0
    def getChild(self, paramspec, request):
        xsls, paths, params = self._parser.parse(paramspec)

        # Load stylesheets
        try:
            stylesheets = [(key, self._repository.load(paths[key]))
                           for key in xsls]
        except XslRepositoryNoCandidateError:
            return resource.NoResource(
                "One of the specified stylesheets was not found on the server")

        if len(stylesheets) == 0:
            return NoStylesheetsResource()

        # Detect the output method of the last stylesheet and map it to
        # content-type.
        method = self._output_method.detect(stylesheets[-1][1])
        content_type = self._content_type_map[method]

        # Tranformations
        transformations = [(key, etree.XSLT(doc)) for key, doc in stylesheets]

        extraction = XslTransformationExtraction(transformations, params,
                                                 content_type)
        return ExtractionReverseProxyResource(extraction, self._backend,
                                              self._hostport, self._path)
示例#13
0
 def getChild(self, name, request):
     if not name:
         return self
     if name in self.route:
         return self.route[name]()
     else:
         return resource.NoResource()
示例#14
0
def _getChild_done(child, parent):
    Message.log(
        message_type=u"allmydata:web:common-getChild:result",
        result=fullyQualifiedName(type(child)),
    )
    if child is None:
        return resource.NoResource()
    return child
示例#15
0
    def getChild(self, path, request):
        fn = os.path.join(self.path, path)

        if os.path.isdir(fn):
            return ResourceScriptDirectory(fn, self.registry)
        if os.path.exists(fn):
            return ResourceScript(fn, self.registry)
        return resource.NoResource()
示例#16
0
文件: resource.py 项目: nagyist/Tron
def resource_from_collection(collection, name, child_resource):
    """Return a child resource from a collection by name.  If no item is found,
    return NoResource.
    """
    item = collection.get_by_name(name)
    if item is None:
        return resource.NoResource("Cannot find child %s" % name)
    return child_resource(item)
示例#17
0
    def getChild(self, path, request):
        if path == 'static':
            return self.static_files
        if path not in self.connections:
            if 'htmlfile' in request.path:
                return transports.htmlfile.CloseResource();
            return resource.NoResource("<script>alert('whoops');</script>")
#        print 'returning self.connections[%s]' % (path,)
        return self.connections[path]
示例#18
0
 def getChild(self, path, req):
     # 0.4.0 used "POST /CID/SIDE/post/MSGNUM"
     # 0.5.0 replaced it with "POST /add (json body)"
     # give a nicer error message to old clients
     if (len(req.postpath) >= 2
             and req.postpath[1] in (b"post", b"poll", b"deallocate")):
         welcome = self._rendezvous.get_welcome()
         return NeedToUpgradeErrorResource(welcome)
     return resource.NoResource("No such child resource.")
示例#19
0
 def getChild(self, path, request):
     try:
         return self.children[path]
     except KeyError:
         # no child found, assume channel id
         try:
             return self.channels[path]
         except KeyError:
             return resource.NoResource()
示例#20
0
文件: www.py 项目: swipswaps/Tron
    def getChild(self, name, request):
        if name == '':
            return self

        found = self._master_control.jobs.get(name)
        if found is None:
            return resource.NoResource("Cannot find job '%s'" % name)

        return JobResource(found, self._master_control)
示例#21
0
 def getChild(self, path, request):
     fnp = self.child(path)
     if not fnp.exists():
         return static.File.childNotFound
     elif fnp.isdir():
         return CGIDirectory(fnp.path)
     else:
         return CGIScript(fnp.path)
     return resource.NoResource()
示例#22
0
 def getChild(self, name, request):
     if request.uri == '/steemauth':
         return SteemAuth(cu, self.account, self.templates, self.reactor,
                          self.log)
     else:
         if request.uri == '/':
             return SetCookieIfNeeded(self.cu)
         else:
             return resource.NoResource()
示例#23
0
	def getChild(self, path, request):
		print("getChild(%s)" % path)
		if path == "":
			return self

		for con in self.containers():
			if con.hostname == path:
				return ContainerService(con)

		return resource.NoResource("Not a valid container hostname")
示例#24
0
 def getChild(self, path, request):
     fnp = self.child(path)
     print fnp.path
     if not fnp.exists():
         return static.File.childNotFound
     elif fnp.isdir():
         return CgiDirectory(fnp.path, self.filter)
     else:
         return self.cgiscript(fnp.path, self.filter)
     return resource.NoResource()
示例#25
0
文件: www.py 项目: swipswaps/Tron
    def getChild(self, act_name, request):
        if act_name == '':
            return self

        for act_run in self._run.runs:
            if act_name == act_run.action.name:
                return ActionRunResource(act_run)

        return resource.NoResource("Cannot find action '%s' for job run '%s'" %
                                   (act_name, self._run.id))
示例#26
0
	def getChild (self, name, request):
		if name == "":
			return self

		try:
			expt = experiments[name]
		except KeyError:
			return resource.NoResource()
		else:
			return ExperimentView(expt, name)
示例#27
0
    def getChild(self, name, req):
        try:
            node = self.dump.get_by_title(name)
        except KeyError:
            try:
                name = name[0].capitalize() + name[1:].replace('_', ' ')
                node = self.dump.get_by_title(name)
            except KeyError:
                return resource.NoResource()

        return self.makeChild(name, node)
示例#28
0
文件: www.py 项目: swipswaps/Tron
    def getChild(self, run_num, request):
        if run_num == '':
            return self

        if run_num.isdigit():
            run = self._job.get_run_by_num(int(run_num))
            if run:
                return JobRunResource(run)

        return resource.NoResource("Cannot run number '%s' for job '%s'" %
                                   (run_num, self._job.name))
示例#29
0
文件: resource.py 项目: nagyist/Tron
    def getChild(self, action_name, _):
        if not action_name:
            return self
        if action_name == '_events':
            return EventResource(self.job_run.id)
        if action_name in self.job_run.action_runs:
            action_run = self.job_run.action_runs[action_name]
            return ActionRunResource(action_run, self.job_run)

        msg = "Cannot find action %s for %s"
        return resource.NoResource(msg % (action_name, self.job_run))
示例#30
0
    def render_GET(self, request):
        key = request.postpath[0]
        if key not in self.file_mapping:
            return resource.NoResource().render(request)

        f = self.file_mapping[key]
        if f.is_complete():
            return static.File(f.full_path).render_GET(request)
        else:
            tfr = f.open()
            return FilelikeObjectResource(tfr, f.size).render_GET(request)