def removeProcessGroup(self, name): from xmlrpc.client import Fault from supervisor import xmlrpc_lib if name == 'STILL_RUNNING': raise Fault(xmlrpc_lib.Faults.STILL_RUNNING, '') if name == 'BAD_NAME': raise Fault(xmlrpc_lib.Faults.BAD_NAME, '') self.processes.remove(name)
def addProcessGroup(self, name): from xmlrpc.client import Fault from supervisor import xmlrpc_lib if name == 'ALREADY_ADDED': raise Fault(xmlrpc_lib.Faults.ALREADY_ADDED, '') if name == 'BAD_NAME': raise Fault(xmlrpc_lib.Faults.BAD_NAME, '') if hasattr(self, 'processes'): self.processes.append(name) else: self.processes = [name]
def stopProcess(self, name): from supervisor import xmlrpc_lib from xmlrpc.client import Fault if name == 'BAD_NAME:BAD_NAME': raise Fault(xmlrpc_lib.Faults.BAD_NAME, 'BAD_NAME:BAD_NAME') if name == 'BAD_NAME': raise Fault(xmlrpc_lib.Faults.BAD_NAME, 'BAD_NAME') if name == 'NOT_RUNNING': raise Fault(xmlrpc_lib.Faults.NOT_RUNNING, 'NOT_RUNNING') if name == 'FAILED': raise Fault(xmlrpc_lib.Faults.FAILED, 'FAILED') return True
def authenticate(username, password, permission=None): """ Authenticate staff_user with permission. """ author = authen(username=username, password=password) if not author: raise Fault(LOGIN_ERROR, _('Username or Password is incorrect.')) if not author.is_staff or not author.is_active: raise Fault(PERMISSION_DENIED, _('User account unavailable.')) if permission: if not author.has_perm(permission): raise Fault(PERMISSION_DENIED, _('User cannot %s.') % permission) return author
def check_perms(user, obj): logger.debug("%s.check_perms entered" % __name__) if isinstance(obj, Post): if obj.author.user != user and not user.is_superuser: raise Fault(PERMISSION_DENIED, 'Permission denied for %s on post %s' % (user, obj.id)) elif isinstance(obj, Blog): if obj.owner != user and not user.is_superuser: raise Fault(PERMISSION_DENIED, 'Permission denied for %s on post %s' % (user, obj.id)) else: raise Fault(PERMISSION_DENIED, 'Permission denied for %s unknown object %s' % (user, obj))
def authenticate(username, password, permission=None): """Authenticate staff_user with permission""" try: author = Author.objects.get(username__exact=username) except Author.DoesNotExist: raise Fault(LOGIN_ERROR, _('Username is incorrect.')) if not author.check_password(password): raise Fault(LOGIN_ERROR, _('Password is invalid.')) if not author.is_staff or not author.is_active: raise Fault(PERMISSION_DENIED, _('User account unavailable.')) if permission: if not author.has_perm(permission): raise Fault(PERMISSION_DENIED, _('User cannot %s.') % permission) return author
def test_forward(self): """ Test the `ipalib.rpc.xmlclient.forward` method. """ class user_add(Command): pass o, _api, _home = self.instance('Backend', user_add, in_server=False) args = (binary_bytes, utf8_bytes, unicode_str) kw = dict(one=binary_bytes, two=utf8_bytes, three=unicode_str) params = [args, kw] result = (unicode_str, binary_bytes, utf8_bytes) conn = DummyClass( ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, rpc.xml_wrap(result, API_VERSION), ), ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, Fault(3007, u"'four' is required"), # RequirementError ), ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, Fault(700, u'no such error'), # There is no error 700 ), ) # Create connection for the current thread setattr(context, o.id, Connection(conn, lambda: None)) context.xmlclient = Connection(conn, lambda: None) # Test with a successful return value: assert o.forward('user_add', *args, **kw) == result # Test with an errno the client knows: e = raises(errors.RequirementError, o.forward, 'user_add', *args, **kw) assert_equal(e.args[0], u"'four' is required") # Test with an errno the client doesn't know e = raises(errors.UnknownError, o.forward, 'user_add', *args, **kw) assert_equal(e.code, 700) assert_equal(e.error, u'no such error') assert context.xmlclient.conn._calledall() is True
def _marshaled_dispatch(self, data, dispatch_method = None, path = None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the preferred means of changing method dispatch behavior. """ try: params, method = loads(data, use_builtin_types=self.use_builtin_types) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Fault as fault: response = dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except BaseException as exc: response = dumps( Fault(1, "%s:%s" % (type(exc), exc)), encoding=self.encoding, allow_none=self.allow_none, ) return response.encode(self.encoding, 'xmlcharrefreplace')
def shutdown(self): if self._restartable: self._shutdown = True return from xmlrpc.client import Fault from supervisor import xmlrpc_lib raise Fault(xmlrpc_lib.Faults.SHUTDOWN_STATE, '')
def raiseFault(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: print(fn.__class__, ":", fn.__name__, "rpc 调用异常(服务器端):", str(e)) traceback.print_exc() raise Fault(0, str(e))
def _mirror_rpms(self, koji_profile, package_names): print('Mirroring RPMs for %r: listed packages in %s' % (self, koji_profile)) hub_url = koji_config.get(koji_profile, 'server') koji_session = koji.ClientSession(hub_url) koji_session.multicall = True for package_name in package_names: # EPEL has some very old builds that are not signed. # As a workaround we only grab the latest tagged build from EPEL. if self.downgradeable and not koji_profile == 'koji': koji_session.listTaggedRPMS(self.package_tags.get( package_name, self.tag), inherit=True, package=package_name) else: koji_session.getLatestRPMS( self.package_tags.get(package_name, self.tag), package_name) results = koji_session.multiCall() for i, result in enumerate(results): if 'faultCode' in result: raise Fault(result['faultCode'], result['faultString']) if not result or not result[0] or not result[0][1]: raise ValueError( 'Package %s not in tag %s in %s' % (package_names[i], self.package_tags.get(package_names[i], self.tag), koji_profile)) (rpms, builds), = result self._mirror_rpms_for_build(koji_profile, builds, rpms)
def test_xml_loads(): """ Test the `ipalib.rpc.xml_loads` function. """ f = rpc.xml_loads params = (binary_bytes, utf8_bytes, unicode_str, None) wrapped = rpc.xml_wrap(params, API_VERSION) # Test un-serializing an RPC request: data = dumps(wrapped, 'the_method', allow_none=True) (p, m) = f(data) assert_equal(m, u'the_method') assert_equal(p, params) # Test un-serializing an RPC response: data = dumps((wrapped, ), methodresponse=True, allow_none=True) (tup, m) = f(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert_equal(tup[0], params) # Test un-serializing an RPC response containing a Fault: for error in (unicode_str, u'hello'): fault = Fault(69, error) data = dumps(fault, methodresponse=True, allow_none=True, encoding='UTF-8') e = raises(Fault, f, data) assert e.faultCode == 69 assert_equal(e.faultString, error) assert type(e.faultString) is unicode
def setPostCategories(postid, username, password, cats=[]): """ mt version of setpostcats takes a primary as argument """ logger.debug("%s.setPostCategories called..." % __name__) logger.debug("Submitted with %s" % cats) user = get_user(username, password) post = Post.objects.get(pk=postid) if post.author.user != user: raise Fault(PERMISSION_DENIED, 'Permission denied for %s on post %s' % (user, post)) logger.debug("Old cats: %s" % post.categories.all()) post.categories.clear() catlist = [] for cat in cats: category = Category.objects.get(pk=cat['categoryId']) # print "Got", category if 'isPrimary' in cat and cat['isPrimary']: logger.debug("Got primary category '%s'" % cat) post.primary_category_name = category post.categories.add(category) logger.debug("New cats: %s" % post.categories.all()) post.save() logger.debug("%s.setPostCategories Done." % __name__) return True
def test_xml_dumps(): """ Test the `ipalib.rpc.xml_dumps` function. """ f = rpc.xml_dumps params = (binary_bytes, utf8_bytes, unicode_str, None) # Test serializing an RPC request: data = f(params, API_VERSION, 'the_method') (p, m) = loads(data) assert_equal(m, u'the_method') assert type(p) is tuple assert rpc.xml_unwrap(p) == params # Test serializing an RPC response: data = f((params, ), API_VERSION, methodresponse=True) (tup, m) = loads(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert rpc.xml_unwrap(tup[0]) == params # Test serializing an RPC response containing a Fault: fault = Fault(69, unicode_str) data = f(fault, API_VERSION, methodresponse=True) e = raises(Fault, loads, data) assert e.faultCode == 69 assert_equal(e.faultString, unicode_str)
def handler(req): # Only accept POST requests if req.method != 'POST': req.content_type = 'text/plain' req.send_http_header() req.write("Not valid XML-RPC POST request") return apache.OK # Fetch the request body = req.read() # Prepare response req.content_type = "text/xml" req.send_http_header() # Process request try: args, method = loads(body) except: fault = Fault(0x001, "Invalid XML-RPC error") req.write(dumps(fault, methodresponse=1)) return apache.OK # Execute it. The calling function is # responsive for responding to the request. Dispatch(req, method, args) return apache.OK
def _cbRender(self, result, request, responseFailed=None): if responseFailed: return if isinstance(result, Handler): result = result.result if not isinstance(result, Fault): result = (result, ) try: try: content = xmlrpclib.dumps(result, methodresponse=True, allow_none=self.allowNone) except Exception as e: f = Fault(self.FAILURE, f"Can't serialize output: {e}") content = xmlrpclib.dumps(f, methodresponse=True, allow_none=self.allowNone) if isinstance(content, str): content = content.encode("utf8") request.setHeader(b"content-length", b"%d" % (len(content), )) request.write(content) except Exception: self._log.failure("") request.finish()
def render_POST(self, request): request.content.seek(0, 0) request.setHeader(b"content-type", b"text/xml; charset=utf-8") try: args, functionPath = xmlrpclib.loads(request.content.read(), use_datetime=self.useDateTime) except Exception as e: f = Fault(self.FAILURE, f"Can't deserialize input: {e}") self._cbRender(f, request) else: try: function = self.lookupProcedure(functionPath) except Fault as f: self._cbRender(f, request) else: # Use this list to track whether the response has failed or not. # This will be used later on to decide if the result of the # Deferred should be written out and Request.finish called. responseFailed = [] request.notifyFinish().addErrback(responseFailed.append) if getattr(function, "withRequest", False): d = defer.maybeDeferred(function, request, *args) else: d = defer.maybeDeferred(function, *args) d.addErrback(self._ebRender) d.addCallback(self._cbRender, request, responseFailed) return server.NOT_DONE_YET
def getUserUUIDbyStatus(u, s): """Get the UUID for a given user, any status""" if userExists(u) and userDatabase[u]["activeStatus"] == s: return {"user": u, "UUID": userDatabase[u]["UUID"]} else: raise Fault( 1, "No {status} user {user} found".format( status="active" if s else "inactive", user=u))
def getUserAllDetails(u): """Get all the user details for a given user""" if userExists(u): result = userDatabase[u] result.update({"user": u}) return result else: raise Fault(1, "No user {} found".format(u))
def _marshaled_dispatch(self, data, dispatch_method=None, path=None): try: response = self.dispatchers[path]._marshaled_dispatch(data, dispatch_method, path) except: (exc_type, exc_value) = sys.exc_info()[:2] response = dumps(Fault(1, '%s:%s' % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none) response = response.encode(self.encoding) return response
def editPost(postid, username, password, struct, publish): LOGGER.debug( "%s.editPost entered", __name__) user = get_user(username, password) post = Post.objects.get(id=postid) if post.author.user != user and not user.is_superuser: raise Fault(PERMISSION_DENIED, 'Permission denied for %s on post %s' % (user, postid)) title = struct.get('title', None) if title is not None: post.title = title body = struct.get('description', None) text_more = struct.get('mt_text_more', '') allow_pings = struct.get('mt_allow_pings',1) description = struct.get('description','') keywords = struct.get('mt_keywords',[]) # check for string or array if type(keywords) == type(""): # it's been passed as a string. Damn you, ecto struct['mt_keywords'] = keywords.split(",") text_more = struct.get('mt_text_more',None) if text_more: # has the extended entry stuff... body = "<!--more-->".join([body, text_more]) post.enable_comments = bool(struct.get('mt_allow_comments',1)==1) post.text_filter = struct.get('mt_convert_breaks','html').lower() if title: post.title = title if body is not None: post.body = body # todo - parse out technorati tags if user: post.author = user.author if publish: post.status = "publish" else: post.status = "draft" setTags(post, struct, key="mt_keywords") post.update_date = now() post.save() LOGGER.debug("--") LOGGER.debug(post) LOGGER.debug(post.tags.all()) # FIXME: do I really want trackbacks? send_pings(post) return True
def test_handle_anitya_version_update_bugzilla_error( self, mock_cmp_upstream_repo, mock_monitored, mock_publish, message ): """ Assert that Nack exception is thrown when bugzilla error happens. """ with mock.patch.object(self.consumer, "bugzilla") as mock_bugzilla: mock_bugzilla.handle = mock.Mock(side_effect=Fault(51, "Error")) self.assertRaises(Nack, self.consumer.handle_anitya_version_update, message)
def xmlrpc_search(self): try: query = self.query_from_xmlrpc(self.request.body) log.debug("xmlrpc_search {0}".format(query)) hits = self.search_index_packages(query) response = dumps((hits, ), methodresponse=1, encoding='utf-8') except Exception as e: log.exception("Error in xmlrpc_search") response = dumps(Fault(1, repr(e)), encoding='utf-8') return Response(response)
def blogger_getRecentPosts(appkey, blogid, username, password, num_posts=50): """ returns a list of recent posts """ logger.debug( "blogger.getRecentPosts called...") user = get_user(username, password) if not is_user_blog(user, blogid): raise Fault(PERMISSION_DENIED, 'Permission denied for %s on blogid %s' % (user, blogid)) blog = Blog.objects.get(id=blogid) posts = blog.post_set.order_by('-pub_date')[:num_posts] return [post_struct(post) for post in posts]
def blogger_deletePost(appkey, post_id, username, password, publish=False): """ deletes the specified post...""" logger.debug("blogger.deletePost called") user = get_user(username, password) post = Post.objects.get(pk=post_id) if post.author.user != user: raise Fault(PERMISSION_DENIED, 'Permission denied for %s on post %s' % (user, postid)) logger.warn("Deleting post %s by user %s" % (post.id, user)) post.delete() return True
def xmlrpc_search(self): try: query = self.query_from_xmlrpc(self.request.body) search_index = self.request.registry['search_index'] context = ContextWrapper(self.request.context) hits = search_index.query_packages(query, list(context.stage.sro())) response = dumps((hits,), methodresponse=1, encoding='utf-8') except Exception as e: log.exception("Error in xmlrpc_search") response = dumps(Fault(1, repr(e)), encoding='utf-8') return Response(response)
def get_user(username, apikey, blogid=None): """ checks if a user is authorized to make this call """ logger.debug("%s.get_user entered" % __name__) logger.debug("user: %s" % username) logger.debug("apikey: %s" % apikey) try: user = User.objects.get(**{'username': username}) except User.DoesNotExist: raise Fault(LOGIN_ERROR, 'Username is incorrect.') if not apikey == user.author.remote_access_key: raise Fault(LOGIN_ERROR, 'Password is invalid.') if not user.author.remote_access_enabled: raise Fault(PERMISSION_DENIED, 'Remote access not enabled for this user.') # if not author.is_staff or not author.is_active: # raise Fault(PERMISSION_DENIED, _('User account unavailable.')) # raise Fault(PERMISSION_DENIED, _('User cannot %s.') % permission) return user
def getPost(post_id, username, password): """ returns an existing post """ LOGGER.debug("metaWeblog.getPost called") user = get_user(username, password) post = Post.objects.get(pk=post_id) if post.author.user != user and not user.is_superuser: raise Fault(PERMISSION_DENIED, 'Permission denied for %s on post %s' % (user, post_id)) # post.create_date = format_date(datetime.datetime.now()) return post_struct(post)
def update(id, comment, attributes={}, notify=False, **kwargs): """ array ticket.update(int id, string comment, struct attributes={}, boolean notify=False) Update a ticket, returning the new ticket in the same form as getTicket(). Requires a valid 'action' in attributes to support workflow. """ from yats.forms import TicketsForm request = kwargs['request'] checkImpersonate(request) params = {} for key, value in attributes.items(): params[TracNameTofieldName(key)] = value ticket = get_ticket_model().objects.get(pk=id) if ticket.closed: return Fault(_('ticket already closed')) fakePOST = QueryDict('', mutable=True) fakePOST.update(params) form = TicketsForm(fakePOST, instance=ticket, is_stuff=request.user.is_staff, user=request.user, customer=request.organisation.id) form.cleaned_data = params form._changed_data = [name for name in params] for key, value in params.items(): setattr(ticket, key, value) if key == 'assigned': touch_ticket(value, ticket.pk) ticket.save(user=request.user) remember_changes(request, form, ticket) touch_ticket(request.user, ticket.pk) if comment: from yats.models import tickets_comments com = tickets_comments() com.comment = _('ticket changed by %(user)s\n\n%(comment)s') % {'user': request.user, 'comment': comment} com.ticket = ticket com.action = 4 com.save(user=request.user) check_references(request, com) if notify: mail_ticket(request, ticket.pk, form, is_api=True) jabber_ticket(request, ticket.pk, form, is_api=True) signal_ticket(request, ticket.pk, form, is_api=True) return get(id, **kwargs)
def dispatch(self, request, *args, **kwargs): rpc_call = loads(request.body.decode('utf-8')) rpc_args = rpc_call[0] method_name = rpc_call[1] try: # noinspection PyCallingNonCallable src_result = self.methods[method_name](request, rpc_args, *args, **kwargs) result = src_result, except Exception as e: result = Fault(e.__class__.__name__, str(e)) data = dumps(result, method_name, True) return HttpResponse(data, content_type='application/xml+rpc')
def __init__(self): Fault.__init__(self, AUTHENTICATION_FAILED_CODE, _('Username and/or password is incorrect'))
def __init__(self): Fault.__init__(self, PERMISSION_DENIED_CODE, _('Permission denied'))
def __init__(self, message="Couldn't handle the query"): Fault.__init__(self, UNHANDLED, message)
def __init__(self, message="Access denied"): Fault.__init__(self, ACCESS_DENIED, message)
def __init__(self, faultString="Acess denied"): Fault.__init__(self, ACCESS_DENIED, faultString)
def __init__(self, faultString="Couldn't handle the query"): Fault.__init__(self, UNHANDLED, faultString)