def response(self, msg): """Sends an UMCP response to the client""" PROTOCOL.info('Sending UMCP RESPONSE %s' % msg.id) self.__queue += bytes(msg) if self._do_send(self.__comm): notifier.socket_add(self.__comm, self._do_send, notifier.IO_WRITE)
def _formattedMessage(_id, _type, mimetype, command, body, arguments): # type: (Text, RequestType, str, str, UmcpBody, List[str]) -> bytes '''Returns formatted message.''' type = b'RESPONSE' if _type == Message.REQUEST: type = b'REQUEST' if mimetype == MIMETYPE_JSON: try: data = json.dumps(body) except TypeError: PROTOCOL.error('Could not JSON serialize message: %r' % (body, )) raise if not isinstance(data, bytes): # Python 3 data = data.encode('utf-8') else: data = bytes(body) args = b'' if arguments: args = b' '.join( x.encode('utf-8') if hasattr(bytes, 'encode' ) else bytes(x, 'utf-8') for x in arguments) return b'%s/%s/%d/%s: %s %s\n%s' % ( type, _id.encode('utf-8'), len(data), mimetype.encode('utf-8'), (command or u'NONE').encode('utf-8'), args, data)
def set_body(self, filename, mimetype=None): '''Set body of response by guessing the mime type of the given file if not specified and adding the content of the file to the body. The mime type is guessed using the extension of the filename.''' if mimetype is None: self.mimetype, encoding = mimetypes.guess_type(filename) else: self.mimetype = mimetype if self.mimetype is None: PROTOCOL.process('Failed to guess MIME type of %s' % filename) raise TypeError(_('Unknown mime type')) with open(filename, 'rb') as fd: # FIXME: should check size first self.body = fd.read()
def handle(self, msg): # type: (Request) -> None """Handles incoming UMCP requests. This function is called only when it is a valid UMCP request. :param Request msg: the received UMCP request The following commands are handled directly and are not passed to the custom module code: * SET (acls|username|credentials) * EXIT """ from ..error import UMC_Error, NotAcceptable self.__time_remaining = self.__timeout PROTOCOL.info('Received UMCP %s REQUEST %s' % (msg.command, msg.id)) resp = Response(msg) resp.status = SUCCESS if msg.command == 'EXIT': shutdown_timeout = 100 MODULE.info("EXIT: module shutdown in %dms" % shutdown_timeout) # shutdown module after one second resp.message = 'module %s will shutdown in %dms' % ( msg.arguments[0], shutdown_timeout) self.response(resp) notifier.timer_add(shutdown_timeout, self._timed_out) return if self.__init_etype: notifier.timer_add(10000, self._timed_out) six.reraise(self.__init_etype, self.__init_exc, self.__init_etraceback) if msg.command == 'SET': for key, value in msg.options.items(): if key == 'acls': self.__acls = ACLs(acls=value) self.__handler.acls = self.__acls elif key == 'commands': self.__commands.fromJSON(value['commands']) elif key == 'username': self.__username = value self.__handler.username = self.__username elif key == 'password': self.__password = value self.__handler.password = self.__password elif key == 'auth_type': self.__auth_type = value self.__handler.auth_type = self.__auth_type elif key == 'credentials': self.__username = value['username'] self.__user_dn = value['user_dn'] self.__password = value['password'] self.__auth_type = value.get('auth_type') self.__handler.username = self.__username self.__handler.user_dn = self.__user_dn self.__handler.password = self.__password self.__handler.auth_type = self.__auth_type elif key == 'locale' and value is not None: try: self.__handler.update_language([value]) except NotAcceptable: pass # ignore if the locale doesn't exists, it continues with locale C else: raise UMC_Error(status=422) # if SET command contains 'acls', commands' and # 'credentials' it is the initialization of the module # process if 'acls' in msg.options and 'commands' in msg.options and 'credentials' in msg.options: MODULE.process('Initializing module.') try: self.__handler.init() except Exception: try: exc_info = sys.exc_info() self.__init_etype, self.__init_exc, self.__init_etraceback = exc_info # FIXME: do not keep a reference to traceback self.error_handling(msg, 'init', *exc_info) finally: exc_info = None return self.response(resp) return if msg.arguments: cmd = msg.arguments[0] cmd_obj = self.command_get(cmd) if cmd_obj and (not self.__check_acls or self.__acls.is_command_allowed( cmd, options=msg.options, flavor=msg.flavor)): self.__active_requests += 1 self.__handler.execute(cmd_obj.method, msg) return raise UMC_Error('Not initialized.', status=403)