当前位置: 首页>>代码示例>>Python>>正文


Python Client.subscribe_events方法代码示例

本文整理汇总了Python中freenas.dispatcher.client.Client.subscribe_events方法的典型用法代码示例。如果您正苦于以下问题:Python Client.subscribe_events方法的具体用法?Python Client.subscribe_events怎么用?Python Client.subscribe_events使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在freenas.dispatcher.client.Client的用法示例。


在下文中一共展示了Client.subscribe_events方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Context

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import subscribe_events [as 别名]
class Context(object):
    def __init__(self):
        self.hostname = None
        self.connection = Client()
        self.ml = None
        self.logger = logging.getLogger('cli')
        self.plugin_dirs = []
        self.task_callbacks = {}
        self.plugins = {}
        self.variables = VariableStore()
        self.root_ns = RootNamespace('')
        self.event_masks = ['*']
        self.event_divert = False
        self.event_queue = six.moves.queue.Queue()
        self.keepalive_timer = None
        self.argparse_parser = None
        config.instance = self

    @property
    def is_interactive(self):
        return os.isatty(sys.stdout.fileno())

    def start(self):
        self.discover_plugins()
        self.connect()

    def connect(self):
        try:
            self.connection.connect(self.hostname)
        except socket_error as err:
            output_msg(_(
                "Could not connect to host: {0} due to error: {1}".format(self.hostname, err)
            ))
            self.argparse_parser.print_help()
            sys.exit(1)

    def login(self, user, password):
        try:
            self.connection.login_user(user, password)
            self.connection.subscribe_events(*EVENT_MASKS)
            self.connection.on_event(self.handle_event)
            self.connection.on_error(self.connection_error)

        except RpcException as e:
            if e.code == errno.EACCES:
                self.connection.disconnect()
                output_msg(_("Wrong username or password"))
                sys.exit(1)

        self.login_plugins()

    def keepalive(self):
        if self.connection.opened:
            self.connection.call_sync('management.ping')

    def read_middleware_config_file(self, file):
        """
        If there is a cli['plugin-dirs'] in middleware.conf use that,
        otherwise use the default plugins dir within cli namespace
        """
        plug_dirs = None
        if file:
            with open(file, 'r') as f:
                data = json.load(f)

            if 'cli' in data and 'plugin-dirs' in data['cli']:

                if type(data['cli']['plugin-dirs']) != list:
                    return

                self.plugin_dirs += data['cli']['plugin-dirs']

        if plug_dirs is None:
            plug_dirs = os.path.dirname(os.path.realpath(__file__))
            plug_dirs = os.path.join(plug_dirs, 'plugins')
            self.plugin_dirs += [plug_dirs]


    def discover_plugins(self):
        for dir in self.plugin_dirs:
            self.logger.debug(_("Searching for plugins in %s"), dir)
            self.__discover_plugin_dir(dir)

    def login_plugins(self):
        for i in list(self.plugins.values()):
            if hasattr(i, '_login'):
                i._login(self)

    def __discover_plugin_dir(self, dir):
        for i in glob.glob1(dir, "*.py"):
            self.__try_load_plugin(os.path.join(dir, i))

    def __try_load_plugin(self, path):
        if path in self.plugins:
            return

        self.logger.debug(_("Loading plugin from %s"), path)
        name, ext = os.path.splitext(os.path.basename(path))
        plugin = imp.load_source(name, path)

#.........这里部分代码省略.........
开发者ID:williambr,项目名称:middleware,代码行数:103,代码来源:repl.py

示例2: BaseTestCase

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import subscribe_events [as 别名]
class BaseTestCase(unittest.TestCase):
    class TaskState(object):
        def __init__(self):
            self.tid = None
            self.state = None
            self.message = None
            self.result = None
            self.name = None
            self.ended = Event()
            

    def __init__(self, methodName):
        super(BaseTestCase, self).__init__(methodName)
        self.tasks = {}
        self.tasks_lock = Lock()
        self.conn = None
        self.task_timeout = 30

    def setUp(self):
        try:
            self.conn = Client()
            self.conn.event_callback = self.on_event
            self.conn.connect(os.getenv('TESTHOST', '127.0.0.1'))
            self.conn.login_user(os.getenv('TESTUSER', 'root'), os.getenv('TESTPWD', ''), timeout = self.task_timeout)
            self.conn.subscribe_events('*')
        except:
            raise

    def tearDown(self):
        self.conn.disconnect()

    def submitTask(self, name, *args):
        with self.tasks_lock:
            try:
                tid = self.conn.call_sync('task.submit', name, args)
            except RpcException:
                raise
            except Exception:
                raise    

            self.tasks[tid] = self.TaskState()
            self.tasks[tid].tid = tid
            self.tasks[tid].name = name
        return tid

    def assertTaskCompletion(self, tid):
        t = self.tasks[tid]
        if not t.ended.wait(self.task_timeout):
            self.fail('Task {0} timed out'.format(tid))
        #print dir(t)    
        #print 'Message is ' + str(t.message)  
        #print 'State is ' + str(t.state)
        #print 'Result is ' + str(t.result)

        if t.state.count('Executing...'):
            message = t.error
        elif t.__getattribute__('message') and t.message.count('Executing...'):
            message = t.state    
        else:
            message = t.message
        if not message:
            self.query_task(tid)
 
        self.assertEqual(t.state, 'FINISHED', msg=message)

    def assertTaskFailure(self, tid):
        t = self.tasks[tid]
        if not t.ended.wait(self.task_timeout):
            self.fail('Task {0} timed out'.format(tid))

        self.assertNotEqual(t.state, 'FINISHED', msg=t.message)

    def assertSeenEvent(self, name, func=None):
        pass

    def skip(self, reason):
        raise unittest.SkipTest(str(reason))      

    def getTaskResult(self, tid):
        t = self.tasks[tid]
        return t.result

    def on_event(self, name, args):

        with self.tasks_lock:
            if name == 'task.updated':
                #DEBUG
                #print 'ARGS IS ' + str(args)
                #print 'TASK LIST IS ' + str(self.tasks)
                #for pc in self.conn.pending_calls.keys():
                #    print 'PENDING CALL METHOD ' + str(self.conn.pending_calls[pc].method) + \
                #    ' and ID ' + str(self.conn.pending_calls[pc].id)

                if args['id'] not in self.tasks.keys():
                    if args['state'] == 'EXECUTING':
                        return
                else:           
                    t = self.tasks[args['id']]
                    t.state = args['state']
                    if t.state in ('FINISHED', 'FAILED'):
#.........这里部分代码省略.........
开发者ID:650elx,项目名称:middleware,代码行数:103,代码来源:shared.py


注:本文中的freenas.dispatcher.client.Client.subscribe_events方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。