def testBinaryProtocolEof(self): """Test that TBinaryProtocol throws an TTransportException when it reaches the end of the stream""" self.eofTestHelper(TBinaryProtocol.TBinaryProtocolFactory()) self.eofTestHelperStress(TBinaryProtocol.TBinaryProtocolFactory())
def FdsFactory(server): processor = fdsapi.Processor(FdsApiHandler(server)) pfactory = TBinaryProtocol.TBinaryProtocolFactory() return TTwisted.ThriftServerFactory(processor, pfactory)
def start_extension(name="<unknown>", version="0.0.0", sdk_version="1.8.0", min_sdk_version="1.8.0"): """Start your extension by communicating with osquery core and starting a thrift server. Keyword arguments: name -- the name of your extension version -- the version of your extension sdk_version -- the version of the osquery SDK used to build this extension min_sdk_version -- the minimum version of the osquery SDK that you can use """ args = parse_cli_params() # Disable logging for the thrift module (can be loud). logging.getLogger('thrift').addHandler(logging.NullHandler()) client = ExtensionClient(path=args.socket) if not client.open(args.timeout): if args.verbose: message = "Could not open socket %s" % args.socket raise ExtensionException( code=1, message=message, ) return ext_manager = ExtensionManager() # try connecting to the desired osquery core extension manager socket try: status = client.extension_manager_client().registerExtension( info=InternalExtensionInfo( name=name, version=version, sdk_version=sdk_version, min_sdk_version=min_sdk_version, ), registry=ext_manager.registry(), ) except socket.error: message = "Could not connect to %s" % args.socket raise ExtensionException( code=1, message=message, ) if status.code is not 0: raise ExtensionException( code=1, message=status.message, ) # Start a watchdog thread to monitor the osquery process. rt = threading.Thread(target=start_watcher, args=(client, args.interval)) rt.daemon = True rt.start() # start a thrift server listening at the path dictated by the uuid returned # by the osquery core extension manager ext_manager.uuid = status.uuid processor = Processor(ext_manager) transport = None if sys.platform == 'win32': transport = TPipeServer(pipe_name="{}.{}".format(args.socket, status.uuid)) else: transport = TSocket.TServerSocket( unix_socket=args.socket + "." + str(status.uuid)) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) server.serve()
def communicate(callback=None): # create client transport = TTornado.TTornadoStreamTransport('localhost', 9090) pfactory = TBinaryProtocol.TBinaryProtocolFactory() client = Calculator.Client(transport, pfactory) # open the transport, bail on error try: yield gen.Task(transport.open) except TTransport.TTransportException as ex: logging.error(ex) if callback: callback() return # ping yield gen.Task(client.ping) print("ping()") # add sum_ = yield gen.Task(client.add, 1, 1) print("1 + 1 = {}".format(sum_)) # make a oneway call without a callback (schedule the write and continue # without blocking) client.zip() print("zip() without callback") # make a oneway call with a callback (we'll wait for the stream write to # complete before continuing) yield gen.Task(client.zip) print("zip() with callback") # calculate 1/0 work = Work() work.op = Operation.DIVIDE work.num1 = 1 work.num2 = 0 try: quotient = yield gen.Task(client.calculate, 1, work) print("Whoa? You know how to divide by zero?") except InvalidOperation as io: print("InvalidOperation: {}".format(io)) # calculate 15-10 work.op = Operation.SUBTRACT work.num1 = 15 work.num2 = 10 diff = yield gen.Task(client.calculate, 1, work) print("15 - 10 = {}".format(diff)) # getStruct log = yield gen.Task(client.getStruct, 1) print("Check log: {}".format(log.value)) # close the transport client._transport.close() if callback: callback()
except (errors.DBInsertionWrongException): logger.info( "[THIRFT SERVER] Insertion in data base NOT correct of request_id" ) except (errors.DDBAlgorithmNotExistException): logger.info("[THIRFT SERVER] Algorithm do not exist") except requests.exceptions.HTTPError as e: logger.info("[THRIFT SERVER] /start not reached DSS {}".format(e)) except Exception as e: logger.info("[THRIFT SERVER]{}".format(e)) if __name__ == "__main__": # run thrift server handler = DssServiceHandler() proc = DssService.Processor(handler) trans_svr = TSocket.TServerSocket(host=globals.MMTURL, port=globals.MMTPORT) #trans_fac = TTransport.TBufferedTransportFactory() trans_fac = TTransport.TFramedTransportFactory() proto_fac = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(proc, trans_svr, trans_fac, proto_fac) logger.info("[THRIFT SERVER] Started in port {}".format(globals.MMTPORT)) print("[THRIFT SERVER] Started in {} port {}".format( globals.MMTURL, globals.MMTPORT)) server.serve()
duration=169, pro=PerfRightsOrg.ASCAP)] return album def enterAlbumGiveaway(self, ctx, email, name): """ Always return success (true) """ return True if __name__ == "__main__": # Declare the protocol stack used for serialization. # Protocol stacks must match between clients and servers. prot_factory = FProtocolFactory(TBinaryProtocol.TBinaryProtocolFactory()) # Create a new server processor. # Incoming requests to the processor are passed to the handler. # Results from the handler are returned back to the client. processor = FStoreProcessor(StoreHandler()) # Optionally add middleware to the processor before starting the server. # add_middleware can take a list or single middleware. processor.add_middleware(logging_middleware) # Create a new music store server using the a tornado handler # and our configured processor and protocol application = tornado.web.Application([ (r"/frugal", FHttpHandler,
class NormalBinaryTest(AbstractTest): protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()
def serialize(thrift_object, protocol_factory=TBinaryProtocol.TBinaryProtocolFactory()): transport = TTransport.TMemoryBuffer() protocol = protocol_factory.getProtocol(transport) thrift_object.write(protocol) return transport.getvalue()
def testBinaryProtocolEof(self): """Test that TBinaryProtocol throws an EOFError when it reaches the end of the stream""" self.eofTestHelper(TBinaryProtocol.TBinaryProtocolFactory()) self.eofTestHelperStress(TBinaryProtocol.TBinaryProtocolFactory())
class HelloWorldHandler(): def __init__(self): pass def ping(self): return 'pong!' def say(self, message): ret = "server received: " + message print(ret) return ret if __name__ == '__main__': handler = HelloWorldHandler() #build your own handler processor = HelloWorld.Processor( handler) ##get a processor from a handler that you built transport = TSocket.TServerSocket('localhost', 9090) #get a server transport tfactory = TTransport.TBufferedTransportFactory( ) ##get a transport factory pfactory = TBinaryProtocol.TBinaryProtocolFactory( ) ##get a protocol factory server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) #get a server from the settings print("begin the server on localhost,9090") server.serve() print("Suspend the service on localhost,9090")
def create_server(): handler = MusicPiThriftHandler() return TServer.TSimpleServer(GenericPiThriftService.Processor(handler), TSocket.TServerSocket(port=port), TTransport.TBufferedTransportFactory(), TBinaryProtocol.TBinaryProtocolFactory())
def run(): parser = argparse.ArgumentParser(description=__doc__, prog='lesedi') parser.add_argument('--version', action='version', version='%(prog)s {}'.format(__version__)) parser.add_argument('--log-file', help='the log file to write to') parser.add_argument('--log-level', default='INFO', type=str.upper, choices=['DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL'], help='the level of logging to use.') parser.add_argument('--config', help='path to the configuration file') parser.add_argument('--host', default=constants.DEFAULT_HOST, help='the TCP interface to listen on') parser.add_argument('--port', default=constants.DEFAULT_PORT, type=int, help='the TCP port to listen on') arguments = parser.parse_args() if not arguments.log_file: logging.basicConfig(stream=sys.stdout, level=arguments.log_level) else: logging.basicConfig(filename=arguments.log_file, format='%(asctime)s [%(levelname)5s]: %(message)s', level=arguments.log_level) logger = logging.getLogger(__name__) if arguments.config: try: config = configparser.ConfigParser() with open(arguments.config, 'r') as f: config.readfp(f) except IOError as e: sys.exit('Error while reading config file "{}"'.format( arguments.config)) else: # If no config is given, assume that all services are running locally. config = { 'aux': { 'host': '127.0.0.1' }, 'dome': { 'host': '127.0.0.1' }, 'focuser': { 'host': '127.0.0.1' }, 'rotator': { 'host': '127.0.0.1' }, 'telescope': { 'host': '127.0.0.1' }, } handler = Handler(config) processor = Service.Processor(handler) transport = TSocket.TServerSocket(host=arguments.host, port=arguments.port) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TThreadedServer(processor, transport, tfactory, pfactory) logger.info('Listening on {}:{}'.format(arguments.host, arguments.port)) try: server.serve() except (KeyboardInterrupt, SystemExit): sys.exit(0) finally: transport.close()
from flask import Flask, request, make_response from thrift.protocol import TBinaryProtocol from thrift.server import TServer from thrift.transport import TTransport from petrabarus import Geometry class GeometryHandler: def distance(self, a, b): return math.sqrt((a.x - b.x)**2 + (a.y - b.y)**2) handler = GeometryHandler() processor = Geometry.Processor(handler) protocol = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TServer(processor, None, None, None, protocol, protocol) app = Flask(__name__) @app.route('/', methods=['POST']) def service(): itrans = TTransport.TMemoryBuffer(request.data) otrans = TTransport.TMemoryBuffer() iprot = server.inputProtocolFactory.getProtocol(itrans) oprot = server.outputProtocolFactory.getProtocol(otrans) server.processor.process(iprot, oprot) return make_response(otrans.getvalue())
if __name__ == '__main__': if os.path.exists('../../service_log'): shutil.rmtree('../../service_log') os.makedirs('../../service_log/info_log') os.makedirs('../../service_log/error_log') info_logger = get_logger(name=__name__ + '_info', filename='../../service_log/info_log/info.log', level='info') error_logger = get_logger(name=__name__ + '_error', filename='../../service_log/error_log/error.log', level='error') # conf_path_1 = '/Users/lix/Desktop/fasic_cv_sdk/pretrained_models/2stems' conf_path_2 = '/Users/lix/Desktop/fasic_cv_sdk/inaSpeechSegmenter' handler = VisionServicesHandler(conf_path_1, conf_path_2, info_logger=info_logger, error_logger=error_logger) processor = VisionServices.Processor(handler) port, worker = get_args() transport = TSocket.TServerSocket(port=port) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory(strictRead=True, strictWrite=False) server = TServer.TThreadedServer(processor, transport, tfactory, pfactory) print('server starting...') server.serve()
def main(): parser = argparse.ArgumentParser("usage: %prog [options]") parser.add_argument('-b', '--bind', dest='host', metavar='ADDR', help='IP addr or hostname to bind to') parser.add_argument('-p', '--port', dest='port', type=int, metavar='PORT', help='port to bind to') parser.add_argument('-d', '--logdir', dest='logdir', metavar='LOGDIR', default='.', help='log DIR') parser.add_argument('-l', '--loglevel', dest='loglevel', metavar='LOGLEVEL', default='DEBUG', help='log flag') parser.add_argument('--thrift', dest='use_thrift', metavar='THRIFT', default=True, help='use thrift or not') parser.add_argument('--gcfg', dest='gcfg', metavar='GMONDCFG', default='/usr/local/etc/gmond.cfg', help='gmond location') args = parser.parse_args() global logger logger = slogger.get_logger(args.logdir, 'logserver', args.loglevel) if args.use_thrift: from common.thrift_gen.log_record import LogCollector from thrift.transport import TSocket from thrift.protocol import TBinaryProtocol from thrift.server import TNonblockingServer perf_rec_queue = Queue.Queue() handler = LogCollectorHandler(perf_rec_queue=perf_rec_queue) processor = LogCollector.Processor(handler) transport = TSocket.TServerSocket(host=args.host, port=args.port) \ if args.port else TSocket.TServerSocket(unix_socket=args.host) tfactory = TBinaryProtocol.TBinaryProtocolFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TNonblockingServer.TNonblockingServer(processor, transport, tfactory, pfactory) collector = PerfCollector(perf_rec_queue, logger) collector.setDaemon(True) collector.start() cfg_path = args.gcfg interval = 60.0 sender = GMetricSender(collector, logger, interval, cfg_path) \ if cfg_path else PerfSender(collector, logger, interval) sender.setDaemon(True) sender.start() logger.info('Starting the server...') server.serve() logger.info('done.') return set_log_dir(args.logdir) if args.port: log_server = LogRecordTCPSocketReceiver(host=args.host, port=args.port) logger.info("About to start tcp log server with port %s", args.port) else: log_server = LogRecordUnixSocketReceiver(host=args.host) logger.info("About to start unix socket log server" " with socket %s", args.host) log_server.serve_until_stopped() log_server.server_close()
def OtsApiFactory(topka): processor = otsapi.Processor(OtsApiHandler(topka)) pfactory = TBinaryProtocol.TBinaryProtocolFactory() return TTwisted.ThriftServerFactory(processor, pfactory)
def wrappee(*args, **kwargs): logging.debug('in decorator before wrapee with flag ' + str(decorator_self._thrift_class.__name__)) dec_name = str( decorator_self._thrift_class.__name__).split(".")[-1] print(dec_name) assert "use_rpc" in kwargs.keys() and "server" in kwargs.keys(), \ "Wrapped function must be subclass of RPC." if "use_rpc" in kwargs.keys() and "server" in kwargs.keys() \ and kwargs["use_rpc"] and kwargs["server"]: from thrift.protocol import TBinaryProtocol from thrift.transport import TSocket from thrift.transport import TTransport from thrift.server import TServer handler = original_clazz(*args, **kwargs) processor = decorator_self._thrift_class.Processor(handler) transport = TSocket.TServerSocket(port=decorator_self._port) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() self.__inst = handler server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) server.setNumThreads(cpu_count() * 4) logging.info("Serving: " + dec_name) server.serve() logging.info('Done: ' + dec_name) elif "use_rpc" in kwargs.keys() and "server" in kwargs.keys() \ and kwargs["use_rpc"] and not kwargs["server"]: from thrift.protocol import TBinaryProtocol from thrift.transport import TSocket from thrift.transport import TTransport from thrift.server import TServer # Make socket self._transport = TSocket.TSocket(host=dec_name, port=decorator_self._port) # Buffering is critical. Raw sockets are very slow self._transport = TTransport.TBufferedTransport( self._transport) # Connect! self._transport.open() # Wrap in a protocol protocol = TBinaryProtocol.TBinaryProtocol(self._transport) # Create a client to use the protocol encoder client = decorator_self._thrift_class.Client(protocol) logging.info("Client (" + dec_name + ") connected to server: " + str(self._transport.isOpen())) return client else: return original_clazz(*args, **kwargs)
def get_server(service, handler, port): processor = service.Processor(handler) transport = TSocket.TServerSocket(port=port) transport_factory = TTransport.TBufferedTransportFactory() protocol_factory = TBinaryProtocol.TBinaryProtocolFactory() return TServer.TSimpleServer(processor, transport, transport_factory, protocol_factory)
def setup_server(self): self.server = DemoServerWrapper( self.test_host, self.test_port, TBinaryProtocol.TBinaryProtocolFactory(), DemoService.Processor(self.handler))
def get_async_server(service, handler, port): processor = service.Processor(handler) transport = TSocket.TServerSocket(port=port) transport_factory = TTransport.TFramedTransport(transport) protocol_factory = TBinaryProtocol.TBinaryProtocolFactory() return TServer.TThreadedServer(processor, transport, transport_factory, protocol_factory)
def __init__(self, processor, handler, config): self._logger = logging.getLogger(__name__) self._section_name = utils.get_module(__name__) self._server = None self._service_name = config.get(self._section_name, "service", required=True) self._port = config.getint(self._section_name, "port", required=True) self._zk_connect_str = config.get(self._section_name, "zk_connect_str", required=True) self._auth_user = config.get(self._section_name, "auth_user", required=True) self._auth_password = config.get(self._section_name, "auth_password", required=True) self._monitor = config.getboolean(self._section_name, "monitor", default=settings.SERVICE_MONITOR) self._c_module_serialize = config.getboolean( self._section_name, "c_module_serialize", default=settings.USE_C_MODULE_SERIALIZE) self._server_name = config.get(self._section_name, "name") self._owner = config.get(self._section_name, "owner") hosts = "%s/%s" % (self._zk_connect_str, settings.DEFAULT_ZK_NAMESPACE_ROOT) self._server_path = "%s/%s" % (self._service_name, settings.DEFAULT_ZK_NAMESPACE_SERVERS) self._statistic_path = "%s/%s/%s" % ( self._service_name, settings.DEFAULT_ZK_NAMESPACE_STATISTICS, settings.DEFAULT_ZK_NAMESPACE_SERVERS) # create zk acl self._acls = [] self._acls.append( make_digest_acl(self._auth_user, self._auth_password, all=True)) self._acls.append(make_acl("world", "anyone", read=True)) # create zk_client self._zkclient = HARpcZKClientManager.make(hosts, config, "server") self._zkclient.add_auth( "digest", "%s:%s" % (self._auth_user, self._auth_password)) # create zkpath if not self._zkclient.exists(self._service_name): self._zkclient.create(self._service_name, makepath=True) if not self._zkclient.exists(self._server_path): self._zkclient.create(self._server_path, acl=self._acls) if not self._zkclient.exists(self._statistic_path): self._zkclient.create(self._statistic_path, makepath=True) self.transport = TSocket.TServerSocket(port=self._port) self.tfactory = TTransport.TBufferedTransportFactory() if self._monitor: self._collector = StatisticsCollector(self._zkclient, config, is_server=True) self._processor = self._statistics_wrapper(processor)(handler) else: self._processor = processor(handler) if self._c_module_serialize: self.pfactory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory() else: self.pfactory = TBinaryProtocol.TBinaryProtocolFactory()
def main(cfg): if cfg.unix: if cfg.addr == "": sys.exit("invalid listener unix domain socket: {}".format( cfg.addr)) else: try: (host, port) = cfg.addr.rsplit(":", 1) port = int(port) except ValueError: sys.exit("invalid listener address: {}".format(cfg.addr)) if cfg.response == "success": handler = SuccessHandler() elif cfg.response == "idl-exception": handler = IDLExceptionHandler() elif cfg.response == "exception": # squelch traceback for the exception we throw logging.getLogger().setLevel(logging.CRITICAL) handler = ExceptionHandler() else: sys.exit("unknown server response mode {0}".format(cfg.response)) processor = Example.Processor(handler) if cfg.service is not None: # wrap processor with multiplexor multi = TMultiplexedProcessor.TMultiplexedProcessor() multi.registerProcessor(cfg.service, processor) processor = multi if cfg.protocol == "finagle": # wrap processor with finagle request/response header handler processor = TFinagleServerProcessor.TFinagleServerProcessor(processor) if cfg.unix: transport = TSocket.TServerSocket(unix_socket=cfg.addr) else: transport = TSocket.TServerSocket(host=host, port=port) if cfg.transport == "framed": transport_factory = TTransport.TFramedTransportFactory() elif cfg.transport == "unframed": transport_factory = TTransport.TBufferedTransportFactory() elif cfg.transport == "header": if cfg.protocol == "binary": transport_factory = THeaderTransport.THeaderTransportFactory( THeaderTransport.T_BINARY_PROTOCOL) elif cfg.protocol == "compact": transport_factory = THeaderTransport.THeaderTransportFactory( THeaderTransport.T_COMPACT_PROTOCOL) else: sys.exit( "header transport cannot be used with protocol {0}".format( cfg.protocol)) else: sys.exit("unknown transport {0}".format(cfg.transport)) if cfg.protocol == "binary": protocol_factory = TBinaryProtocol.TBinaryProtocolFactory() elif cfg.protocol == "compact": protocol_factory = TCompactProtocol.TCompactProtocolFactory() elif cfg.protocol == "json": protocol_factory = TJSONProtocol.TJSONProtocolFactory() elif cfg.protocol == "finagle": protocol_factory = TFinagleServerProtocol.TFinagleServerProtocolFactory( ) else: sys.exit("unknown protocol {0}".format(cfg.protocol)) print("Thrift Server listening on {0} for {1} {2} requests".format( cfg.addr, cfg.transport, cfg.protocol)) if cfg.service is not None: print("Thrift Server service name {0}".format(cfg.service)) if cfg.response == "idl-exception": print("Thrift Server will throw IDL exceptions when defined") elif cfg.response == "exception": print("Thrift Server will throw Thrift exceptions for all messages") server = TServer.TThreadedServer(processor, transport, transport_factory, protocol_factory) try: server.serve() except KeyboardInterrupt: print
from thrift.server import TServer # 接口实现 class ProductServiceHandler: def printProductName(self): print("你调用到了打印产品名称的方法") def getProductDesc(self, name): s = "你获得产品名称为" + name + "的描述" print(s) return s def isHaveStock(self): print("顾客是上帝,你想要,我们绝对不会缺货") return True #对接thrift if __name__ == '__main__': handler = ProductServiceHandler() processor = ProductService.Processor(handler) # 根据handler创建一个processor transport = TSocket.TServerSocket("127.0.0.1", "9090") # 指定端口启动transport tfactory = TTransport.TBufferedTransportFactory() #按buffer传输 # tfactory = TTransport.TFramedTransportFactory() #按帧传输 pfactory = TBinaryProtocol.TBinaryProtocolFactory() #按二进制传输协议 server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print("------ running -----") server.serve() print("------ over -----")
def main(args=None): if args is None: args = sys.argv if len(args) == 1: usage(args) return 1 try: opts, extraArgs = getopt.getopt(args[1:], 's:t:u:d:', ['sessionId=', 'target=', 'user='******'domain=', 'targetId=', 'keys=', 'no-mouse', 'no-keyboard', 'no-input', 'title=', 'message='] ) except getopt.GetoptError as err: sys.stderr.write('error parsing args: {0}'.format(err)); return 1 sessionId = int(os.environ.get('OGON_SID', '0')) targetServer = ('127.0.0.1', 9091) targetId = None authUser = None authDomain = '' authPassword = None keySeq = wtsapi.VK_F10 keyModifiers = wtsapi.REMOTECONTROL_KBDALT_HOTKEY shadowFlags = 0 userTitle = None userMessage = None userWait = True for option, value in opts: if option in ('-s', '--sessionId',): sessionId = int(value) elif option in ('-t', '--target',): tokens = value.split(':', 2) targetServer = (tokens[0], int(tokens[1])) elif option in ('--targetId',): targetId = int(value) elif option in ('-u', '--user',): tokens = value.split('@', 2) authUser = tokens[0] if len(tokens) > 1: authDomain = tokens[1] elif option in ('-d', '--domain',): authDomain = value elif option in ('--keys',): tokens = value.split('+') keyModifiers = 0 keySeq = 0 for k in tokens: if k in modifiersNames: keyModifiers |= modifiersNames[k] elif k in wtsapi.VK: keySeq = wtsapi.VK[k] if keySeq == 0: print('missing key in key sequence') sys.exit(1) elif option in ('--no-mouse',): shadowFlags |= wtsapi.REMOTECONTROL_FLAG_DISABLE_MOUSE elif option in ('--no-keyboard',): shadowFlags |= wtsapi.REMOTECONTROL_FLAG_DISABLE_KEYBOARD elif option in ('--no-input',): shadowFlags |= wtsapi.REMOTECONTROL_FLAG_DISABLE_INPUT elif option in ('--title',): userTitle = value elif option in ('--message',): userMessage = value elif option in ('--nowait',): userWait = False else: print('unknown option {0}'.format(option)) sys.exit(1) if not len(extraArgs): usage(args) sys.exit(1) authPassword = authUser command = extraArgs[0] @inlineCallbacks def executeCommand(conn): try: # ping the topka to see if it is running client = conn.client ret = yield client.ping(0xff) if ret != 0xff: raise Exception('topka sessionManager not running') doKillToken = False authToken = '' if command in ('listSessions', 'logoffSession', 'sessionDetails', 'startShadowing', 'stopShadowing', 'sendMessage',): # commands that need the authentication token (doKillToken, authToken) = yield getAuthToken(client, authUser, authDomain, authPassword) if command == 'getVersion': v = TVersion(1, 1) ret = yield client.getVersionInfo(v) print("remote version is {0}.{1}".format(ret.VersionMajor, ret.VersionMinor)) elif command == 'listSessions': print("listing sessions:") ret = yield client.enumerateSessions(authToken, 1) if not ret.returnValue: print('error listing sessions') else: print('id\tstate\thostname') for s in ret.sessionInfoList: state = sessionStateNames.get(s.connectState, "<unknown {0}>".format(s.connectState)) print("{0}\t{1}\t{2}".format(s.sessionId, state, s.winStationName)) print('{0} sessions'.format(len(ret.sessionInfoList))) elif command == 'logoffSession': # bool logoffSession(1:TSTRING authToken, 2:TDWORD sessionId, 3:TBOOL wait); ret = yield client.logoffSession(authToken, sessionId, True) print("loggingOff session {0}: {1}".format(sessionId, ret and 'success' or 'failure')) elif command == 'sessionDetails': ret = yield client.querySessionInformation(authToken, sessionId, wtsapi.WTSSessionInfo) if not ret.returnValue: print("an error occured when querying session informations") else: wtsinfo = ret.infoValue.WTSINFO print ("session details for {0}:".format(wtsinfo.SessionId)) if wtsinfo.UserName: fullUser = wtsinfo.UserName + "@" + wtsinfo.Domain else: fullUser = "******" currentTime = wtsinfo.CurrentTime print(" * state: {0}".format( sessionStateNames.get(wtsinfo.State, "<unknown {0}>".format(wtsinfo.State))) ) print(" * user/domain: {0}".format(fullUser)) print(" * stationName: {0}".format(wtsinfo.WinStationName)) connectTime = utils.fromFileTime(wtsinfo.ConnectTime) print(" * connect time: {0}".format(time.strftime("%H:%M:%S-%d %b %Y", connectTime))) print(" * traffic stats: in={0}({1}) out={2}({3})" .format(wtsinfo.IncomingBytes, wtsinfo.IncomingFrames, wtsinfo.OutgoingBytes, wtsinfo.OutgoingFrames)) elif command == 'startShadowing': ret = yield client.startRemoteControlSession(authToken, sessionId, targetId, keySeq, keyModifiers, shadowFlags) if not ret: print ('error enabling shadowing') elif command == 'stopShadowing': ret = yield client.stopRemoteControlSession(authToken, sessionId, targetId) if not ret: print ('error stopping shadowing') elif command == 'sendMessage': ret = yield client.sendMessage(authToken, sessionId, userTitle, userMessage, wtsapi.MB_OK, 10, userWait); if doKillToken: ret = yield client.logoffConnection(authToken) if not ret: print("unable to kill authenticated connection") except: traceback.print_exc() reactor.stop() def connectError(e): print('error={0}'.format(e)) reactor.stop() client = ClientCreator(reactor, TTwisted.ThriftClientProtocol, otsapi.Client, TBinaryProtocol.TBinaryProtocolFactory(), ).connectSSL(targetServer[0], targetServer[1], ssl.ClientContextFactory()) client.addCallbacks(executeCommand, connectError) reactor.run() return 0
class NormalBinaryTest(AbstractTest, unittest.TestCase): protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()
def protocol(self, trans): return TBinaryProtocol.TBinaryProtocolFactory().getProtocol(trans)
def start_service(api_class, service_class, log, services=None, host='localhost', port=9100, killprocgrp=False): """Start a Data API service. Args: api_class (BaseService): The custom API service class, e.g., `doekbase.data_api.taxonomy.taxon.api.TaxonService` service_class (type): The Thrift auto-generated service class log (logging.Logger): Logging object services (dict): Service configuration dictionary, passed to constructor of the `api_class`. host (str): Service host (will default to 'localhost') port (int): Service port, e.g. 9101 killprocgrp (bool): if True, kill process group on exit """ assert issubclass(api_class, BaseService), \ 'Invalid "api_class": must be a subclass of ' \ 'doekbase.data_api.service_core.BaseService' assert hasattr(service_class, 'Processor'), 'Invalid "service_class": ' \ 'missing "Processor" attribute' assert isinstance(port, int), 'The "port" must be an integer' svc_t0 = util.log_start(log, 'start_service', kvp=dict(host=host, port=port)) # Create server services = services or SERVICES_DICT handler = api_class(services) processor = service_class.Processor(handler) pfactory = TBinaryProtocol.TBinaryProtocolFactory() resource = TTwisted.ThriftResource(processor, pfactory, pfactory) site = twisted.web.server.Site(resource=resource) twisted.internet.reactor.listenTCP(port, site, interface=host) # Kill entire process group on shutdown if killprocgrp: twisted.internet.reactor.addSystemEventTrigger( 'before', 'shutdown', functools.partial(kill_process_group, log=log)) # Run server sname = api_class.__name__ shost = host or 'localhost' util.log_start(log, 'server', kvp=dict(name=sname, host=shost, port=port)) t0 = util.log_start(log, 'twisted.internet.reactor.run', level=logging.DEBUG) try: twisted.internet.reactor.run() except Exception as err: log.error('msg="Abort {} server on error"'.format(sname)) util.log_end(log, t0, 'twisted.internet.reactor.run', status_code=1, level=logging.ERROR, kvp=dict(msg=err)) raise finally: util.log_end(log, t0, 'twisted.internet.reactor.run') util.log_end(log, svc_t0, 'start_service', kvp=dict(host=host, port=port)) return 0
def create_server(): handler = ShortTermMemoryThriftServer() return TServer.TSimpleServer(ShortMemoryService.Processor(handler), TSocket.TServerSocket(port=port), TTransport.TBufferedTransportFactory(), TBinaryProtocol.TBinaryProtocolFactory())
# setup root logger to catch any warnings and errors. Most models will override and/or add to these settings. logging.basicConfig(level=logging.WARNING) model_module_name = sys.argv[1] model_class_name = sys.argv[2] model_module = importlib.import_module(model_module_name) model_class = getattr(model_module, model_class_name) model = model_class() handler = ModelHandler(model) processor = Processor(handler) transport = TSocket.TServerSocket(host=sys.argv[3], port=sys.argv[4]) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) signal.signal(signal.SIGINT, handleSIGINT) logger.info(server) logger.info("serving") server.serve() logger.info("done")
def __init__(self): handler = ServiceLocator() processor = TServiceLocator.Processor(handler) pfactory = TBinaryProtocol.TBinaryProtocolFactory() super(TLocatorServer, self).__init__(processor, pfactory)