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


Python Client.connect方法代码示例

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


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

示例1: process_request

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
    def process_request(self, req, resp):
        # Do not require auth to access index
        if req.relative_uri == '/':
            return

        auth = req.get_header("Authorization")
        if auth is None or not auth.startswith('Basic '):
            raise falcon.HTTPUnauthorized(
                'Authorization token required',
                'Provide a Basic Authentication header',
                ['Basic realm="FreeNAS"'],
            )
        try:
            username, password = base64.b64decode(auth[6:]).decode('utf8').split(':', 1)
        except binascii.Error:
            raise falcon.HTTPUnauthorized(
                'Invalid Authorization token',
                'Provide a valid Basic Authentication header',
                ['Basic realm="FreeNAS"'],
            )

        try:
            client = Client()
            client.connect('unix:')
            client.login_user(username, password, check_password=True)
            req.context['client'] = client
        except RpcException as e:
            if e.code == errno.EACCES:
                raise falcon.HTTPUnauthorized(
                    'Invalid credentials',
                    'Verify your credentials and try again.',
                    ['Basic realm="FreeNAS"'],
                )
            raise falcon.HTTPUnauthorized('Unknown authentication error', str(e), ['Basic realm="FreeNAS"'])
开发者ID:freenas,项目名称:middleware,代码行数:36,代码来源:main.py

示例2: get_replication_client

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
def get_replication_client(dispatcher, remote):
    host = dispatcher.call_sync(
        'peer.query',
        [('address', '=', remote), ('type', '=', 'replication')],
        {'single': True}
    )
    if not host:
        raise TaskException(errno.ENOENT, 'There are no known keys to connect to {0}'.format(remote))

    with open('/etc/replication/key') as f:
        pkey = RSAKey.from_private_key(f)

    credentials = host['credentials']

    try:
        client = Client()
        with tempfile.NamedTemporaryFile('w') as host_key_file:
            host_key_file.write(credentials['hostkey'])
            host_key_file.flush()
            client.connect(
                'ws+ssh://[email protected]{0}'.format(remote),
                port=credentials['port'],
                host_key_file=host_key_file.name,
                pkey=pkey
            )
        client.login_service('replicator')
        return client

    except (AuthenticationException, SSHException):
        raise TaskException(errno.EAUTH, 'Cannot connect to {0}'.format(remote))
    except (OSError, ConnectionRefusedError):
        raise TaskException(errno.ECONNREFUSED, 'Cannot connect to {0}'.format(remote))
    except IOError:
        raise TaskException(errno.EINVAL, 'Provided host key is not valid')
开发者ID:650elx,项目名称:middleware,代码行数:36,代码来源:utils.py

示例3: SyslogProvider

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
class SyslogProvider(Provider):
    def initialize(self, context):
        self.client = Client()
        self.client.connect('unix:///var/run/logd.sock')

    @generator
    def query(self, filter=None, params=None):
        return self.client.call_sync('logd.logging.query', filter, params)
开发者ID:erinix,项目名称:middleware,代码行数:10,代码来源:LoggingPlugin.py

示例4: main

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
def main(name, *args):
    connection = Client()
    connection.connect('127.0.0.1')
    connection.login_service('ups')

    connection.emit_event('service.ups.signal', {
        'name': name,
        'type': os.environ['NOTIFYTYPE'],
    })

    connection.disconnect()
开发者ID:650elx,项目名称:middleware,代码行数:13,代码来源:custom-upssched-cmd.py

示例5: main

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
def main(*args):
    connection = Client()
    connection.connect("127.0.0.1")
    connection.login_service("smtp")

    parser = argparse.ArgumentParser(description="Process email")
    parser.add_argument("-i", dest="strip_leading_dot", action="store_false", default=True, help="see sendmail(8) -i")
    parser.add_argument(
        "-t", dest="parse_recipients", action="store_true", default=False, help="parse recipients from message"
    )
    parser.usage = " ".join(parser.format_usage().split(" ")[1:-1])
    parser.usage += " [email_addr|user] .."
    args, to_addrs = parser.parse_known_args()
    if not to_addrs and not args.parse_recipients:
        parser.exit(message=parser.format_usage())
    msg = sys.stdin.read()

    em_parser = email.parser.Parser()
    em = em_parser.parsestr(msg)
    if args.parse_recipients:
        # Strip away the comma based delimiters and whitespace.
        to_addrs = map(str.strip, em.get("To").split(","))

    if not to_addrs or not to_addrs[0]:
        to_addrs = ["root"]

    margs = {}
    margs["extra_headers"] = dict(em)
    margs["extra_headers"].update({"X-Mailer": "FreeNAS", "X-FreeNAS-Host": socket.gethostname()})
    margs["subject"] = em.get("Subject")

    if em.is_multipart():
        margs["attachments"] = filter(lambda part: part.get_content_maintype() != "multipart", em.walk())
        margs["message"] = (
            "This is a MIME formatted message.  If you see "
            "this text it means that your email software "
            "does not support MIME formatted messages."
        )
    else:
        margs["message"] = "".join(email.iterators.body_line_iterator(em))

    if to_addrs:
        margs["to"] = to_addrs

    connection.call_sync("mail.send", margs)
    connection.disconnect()
开发者ID:freenas,项目名称:middleware,代码行数:48,代码来源:find_alias_for_smtplib.py

示例6: get_freenas_peer_client

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
def get_freenas_peer_client(parent, remote):
    try:
        address = socket.gethostbyname(remote)
    except socket.error as err:
        raise TaskException(err.errno, '{0} is unreachable'.format(remote))

    host = parent.dispatcher.call_sync(
        'peer.query', [
            ('or', [
                ('credentials.address', '=', remote),
                ('credentials.address', '=', address),
            ]),
            ('type', '=', 'freenas')
        ],
        {'single': True}
    )
    if not host:
        raise TaskException(errno.ENOENT, 'There are no known keys to connect to {0}'.format(remote))

    with io.StringIO() as f:
        f.write(parent.configstore.get('peer.freenas.key.private'))
        f.seek(0)
        pkey = RSAKey.from_private_key(f)

    credentials = host['credentials']

    try:
        client = Client()
        with tempfile.NamedTemporaryFile('w') as host_key_file:
            host_key_file.write(remote + ' ' + credentials['hostkey'])
            host_key_file.flush()
            client.connect(
                'ws+ssh://[email protected]{0}'.format(wrap_address(remote)),
                port=credentials['port'],
                host_key_file=host_key_file.name,
                pkey=pkey
            )
        client.login_service('replicator')
        return client

    except (AuthenticationException, SSHException):
        raise TaskException(errno.EAUTH, 'Cannot connect to {0}'.format(remote))
    except OSError as err:
        raise TaskException(errno.ECONNREFUSED, 'Cannot connect to {0}: {1}'.format(remote, err))
开发者ID:freenas,项目名称:middleware,代码行数:46,代码来源:utils.py

示例7: BaseTestCase

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
class BaseTestCase(unittest.TestCase):
    def __init__(self, methodName):
        super(BaseTestCase, self).__init__(methodName)
        self.context = None

    def setUp(self):
        super(BaseTestCase, self).setUp()

        assert self.context is not None
        self.ssh_client = self.context.ssh_client
        self.client = Client()
        self.client.connect('ws://{0}'.format(self.context.hostname))
        self.client.login_user(self.context.username, self.context.password)
        load_schema_definitions(self.client)

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

    def ssh_exec(self, command, output=False):
        _, stdout, stderr = self.ssh_client.exec_command(command)
        exitcode = stdout.channel.recv_exit_status()
        if output:
            return exitcode, stdout.read(), stderr.read()

        return exitcode

    def get_params_schema(self, method):
        return get_methods(self.client, method).get('params-schema')

    def get_result_schema(self, method):
        return get_methods(self.client, method).get('results-schema')

    def assertConformsToSchema(self, obj, schema, strict=False):
        errors = verify_schema(schema, obj, strict)
        if errors:
            raise AssertionError('Object {0} does not match {1} schema. Errors: {2}'.format(obj, schema, errors))

    def assertConformsToNamedSchema(self, obj, schema_name, strict=False):
        schema = get_schema(schema_name)
        if not schema:
            raise AssertionError('Schema {0} is unknown'.format(schema_name))
        self.assertConformsToSchema(obj, schema, strict)
开发者ID:erinix,项目名称:middleware,代码行数:44,代码来源:base.py

示例8: test_back_to_back

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
    def test_back_to_back(self):
        a, b = socket.socketpair()
        self.assertGreaterEqual(a.fileno(), 0)
        self.assertGreaterEqual(b.fileno(), 0)

        c1 = Client()
        c1.standalone_server = True
        c1.enable_server()
        c1.register_service('test', TestService())
        c1.connect('fd://{0}'.format(a.fileno()))
        self.assertTrue(c1.connected)

        c2 = Client()
        c2.connect('fd://{0}'.format(b.fileno()))
        self.assertTrue(c2.connected)
        self.assertEqual(c2.call_sync('test.hello', 'freenas'), 'Hello World, freenas')

        c2.disconnect()
        a.close()
        c1.disconnect()
        b.close()
开发者ID:freenas,项目名称:dispatcher-client,代码行数:23,代码来源:transport.py

示例9: test_unix_server

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
    def test_unix_server(self):
        sockpath = os.path.join(os.getcwd(), 'test.{0}.sock'.format(os.getpid()))
        sockurl = 'unix://' + sockpath

        context = RpcContext()
        context.register_service('test', TestService)
        server = Server()
        server.rpc = context
        server.start(sockurl)
        threading.Thread(target=server.serve_forever, daemon=True).start()

        # Spin until server is ready
        while not os.path.exists(sockpath):
            time.sleep(0.1)

        client = Client()
        client.connect(sockurl)
        self.assertTrue(client.connected)
        self.assertEqual(client.call_sync('test.hello', 'freenas'), 'Hello World, freenas')

        client.disconnect()
        server.close()
        os.unlink(sockpath)
开发者ID:freenas,项目名称:dispatcher-client,代码行数:25,代码来源:transport.py

示例10: LogdLogHandler

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
class LogdLogHandler(logging.Handler):
    def __init__(self, level=logging.NOTSET, address=None, ident=None):
        super(LogdLogHandler, self).__init__(level)
        self.address = address or 'unix:///var/run/logd.sock'
        self.ident = ident or os.path.basename(sys.executable)
        self.client = Client()
        self.client.connect(self.address)

    def emit(self, record):
        try:
            if not self.client.connected:
                self.client.connect(self.address)

            item = {
                'timestamp': datetime.utcfromtimestamp(record.created),
                'priority': PRIORITY_MAP.get(record.levelno, 'INFO'),
                'message': record.getMessage(),
                'identifier': self.ident,
                'thread': record.threadName,
                'tid': record.thread,
                'module_name': record.name,
                'source_language': 'python',
                'source_file': record.pathname,
                'source_line': record.lineno,
            }

            if record.exc_info:
                item['exception'] = ''.join(traceback.format_exception(*record.exc_info))

            self.client.call_async('logd.logging.push', None, item)
        except:
            self.handleError(record)

    def close(self):
        super(LogdLogHandler, self).close()
        self.client.disconnect()
开发者ID:erinix,项目名称:middleware,代码行数:38,代码来源:logd.py

示例11: setup_back_to_back

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
    def setup_back_to_back(self, streaming=False):
        a, b = socket.socketpair()
        self.assertGreaterEqual(a.fileno(), 0)
        self.assertGreaterEqual(b.fileno(), 0)

        c1 = Client()
        c1._s = a
        c1.enable_server()
        c1.standalone_server = True

        if streaming:
            c1.streaming = True
            c1.rpc.streaming_enabled = True
        c1.register_service('test', TestService())
        c1.connect('fd://{0}'.format(a.fileno()))
        self.assertTrue(c1.connected)

        c2 = Client()
        c2._s = b
        c2.streaming = True
        c2.connect('fd://{0}'.format(b.fileno()))
        self.assertTrue(c2.connected)

        return c1, c2
开发者ID:freenas,项目名称:dispatcher-client,代码行数:26,代码来源:rpc.py

示例12: run

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
    def run(self, peer, initial_credentials):
        hostid = self.dispatcher.call_sync('system.info.host_uuid')
        hostname = self.dispatcher.call_sync('system.general.get_config')['hostname']
        remote_peer_name = hostname
        credentials = peer['credentials']
        remote = credentials.get('address')
        port = credentials.get('port', 22)
        username = initial_credentials.get('username')
        password = initial_credentials.get('password')
        auth_code = initial_credentials.get('auth_code')
        key_auth = initial_credentials.get('key_auth')

        local_ssh_config = self.dispatcher.call_sync('service.sshd.get_config')

        if self.datastore.exists('peers', ('credentials.address', '=', remote), ('type', '=', 'freenas')):
            raise TaskException(
                errno.EEXIST,
                'FreeNAS peer entry for {0} already exists'.format(remote)
            )

        remote_client = Client()

        try:
            if auth_code:
                try:
                    remote_client.connect('ws://{0}'.format(wrap_address(remote)))
                except (AuthenticationException, OSError, ConnectionRefusedError):
                    raise TaskException(errno.ECONNABORTED, 'Cannot connect to {0}:{1}'.format(remote, port))

                try:
                    remote_host_uuid, pubkey = remote_client.call_sync(
                        'peer.freenas.auth_with_code',
                        auth_code,
                        hostname,
                        local_ssh_config['port']
                    )
                except RpcException as err:
                    raise TaskException(err.code, err.message)

                try:
                    self.dispatcher.call_sync('peer.freenas.put_temp_pubkey', pubkey)
                    if not self.dispatcher.test_or_wait_for_event(
                        'peer.changed',
                        lambda ar: ar['operation'] == 'create' and remote_host_uuid in ar['ids'],
                        lambda: self.datastore.exists('peers', ('id', '=', remote_host_uuid)),
                        timeout=30
                    ):
                        raise TaskException(
                            errno.EAUTH,
                            'FreeNAS peer creation failed. Check connection to host {0}.'.format(remote)
                        )
                finally:
                    self.dispatcher.call_sync('peer.freenas.remove_temp_pubkey', pubkey)

            else:
                try:
                    if key_auth:
                        with io.StringIO() as f:
                            f.write(self.configstore.get('peer.freenas.key.private'))
                            f.seek(0)
                            pkey = RSAKey.from_private_key(f)

                        max_tries = 50
                        while True:
                            try:
                                remote_client.connect('ws+ssh://[email protected]{0}'.format(
                                    wrap_address(remote)), pkey=pkey, port=port
                                )
                                break
                            except AuthenticationException:
                                if max_tries:
                                    max_tries -= 1
                                    time.sleep(1)
                                else:
                                    raise
                    else:
                        remote_client.connect(
                            'ws+ssh://{0}@{1}'.format(username, wrap_address(remote)),
                            port=port,
                            password=password
                        )

                    remote_client.login_service('replicator')
                except (AuthenticationException, OSError, ConnectionRefusedError):
                    raise TaskException(errno.ECONNABORTED, 'Cannot connect to {0}:{1}'.format(remote, port))

                local_host_key, local_pub_key = self.dispatcher.call_sync('peer.freenas.get_ssh_keys')
                remote_host_key, remote_pub_key = remote_client.call_sync('peer.freenas.get_ssh_keys')
                ip_at_remote_side = remote_client.local_address[0]

                remote_hostname = remote_client.call_sync('system.general.get_config')['hostname']

                remote_host_key = remote_host_key.rsplit(' ', 1)[0]
                local_host_key = local_host_key.rsplit(' ', 1)[0]

                if remote_client.call_sync('peer.query', [('id', '=', hostid)]):
                    raise TaskException(errno.EEXIST, 'Peer entry of {0} already exists at {1}'.format(hostname, remote))

                peer['credentials'] = {
                    '%type': 'freenas-credentials',
#.........这里部分代码省略.........
开发者ID:piotrgl,项目名称:middleware,代码行数:103,代码来源:PeerFreeNASPlugin.py

示例13: run

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
    def run(self, peer):
        if self.datastore.exists('peers', ('address', '=', peer['address']), ('type', '=', 'replication')):
            raise TaskException(errno.EEXIST, 'Replication peer entry for {0} already exists'.format(peer['address']))

        if peer['credentials']['type'] != 'ssh':
            raise TaskException(errno.EINVAL, 'SSH credentials type is needed to perform replication peer pairing')

        remote = peer.get('address')
        credentials = peer['credentials']
        username = credentials.get('username')
        port = credentials.get('port', 22)
        password = credentials.get('password')

        if not username:
            raise TaskException(errno.EINVAL, 'Username has to be specified')

        if not remote:
            raise TaskException(errno.EINVAL, 'Address of remote host has to be specified')

        if not password:
            raise TaskException(errno.EINVAL, 'Password has to be specified')

        remote_client = Client()
        try:
            try:
                remote_client.connect('ws+ssh://{0}@{1}'.format(username, remote), port=port, password=password)
                remote_client.login_service('replicator')
            except (AuthenticationException, OSError, ConnectionRefusedError):
                raise TaskException(errno.ECONNABORTED, 'Cannot connect to {0}:{1}'.format(remote, port))

            local_keys = self.dispatcher.call_sync('peer.get_ssh_keys')
            remote_keys = remote_client.call_sync('peer.get_ssh_keys')
            ip_at_remote_side = remote_client.call_sync('management.get_sender_address').split(',', 1)[0]

            remote_host_key = remote + ' ' + remote_keys[0].rsplit(' ', 1)[0]
            local_host_key = ip_at_remote_side + ' ' + local_keys[0].rsplit(' ', 1)[0]

            local_ssh_config = self.dispatcher.call_sync('service.sshd.get_config')

            if remote_client.call_sync('peer.query', [('name', '=', peer['name'])]):
                raise TaskException(errno.EEXIST, 'Peer entry {0} already exists at {1}'.format(peer['name'], remote))

            peer['credentials'] = {
                'pubkey': remote_keys[1],
                'hostkey': remote_host_key,
                'port': port,
                'type': 'replication'
            }

            self.join_subtasks(self.run_subtask(
                'peer.replication.create_local',
                peer
            ))

            peer['address'] = ip_at_remote_side
            peer['credentials'] = {
                'pubkey': local_keys[1],
                'hostkey': local_host_key,
                'port': local_ssh_config['port'],
                'type': 'replication'
            }

            id = self.datastore.query('peers', ('name', '=', peer['name']), select='id')
            try:
                call_task_and_check_state(
                    remote_client,
                    'peer.replication.create_local',
                    peer
                )
            except TaskException:
                self.datastore.delete('peers', id)
                self.dispatcher.dispatch_event('peer.changed', {
                    'operation': 'delete',
                    'ids': [id]
                })
                raise
        finally:
            remote_client.disconnect()
开发者ID:abwaters,项目名称:middleware,代码行数:80,代码来源:PeerPlugin.py

示例14: Context

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [as 别名]
class Context(object):
    def __init__(self):
        self.service = TaskProxyService(self)
        self.task = queue.Queue(1)
        self.datastore = None
        self.configstore = None
        self.conn = None
        self.instance = None
        self.running = Event()

    def put_status(self, state, result=None, exception=None):
        obj = {
            'status': state,
            'result': None
        }

        if result is not None:
            obj['result'] = result

        if exception is not None:
            obj['error'] = serialize_error(exception)

        self.conn.call_sync('task.put_status', obj)

    def task_progress_handler(self, args):
        if self.instance:
            self.instance.task_progress_handler(args)

    def collect_fds(self, obj):
        if isinstance(obj, dict):
            for v in obj.values():
                if isinstance(v, FileDescriptor):
                    yield v
                else:
                    yield from self.collect_fds(v)

        if isinstance(obj, (list, tuple)):
            for o in obj:
                if isinstance(o, FileDescriptor):
                    yield o
                else:
                    yield from self.collect_fds(o)

    def close_fds(self, fds):
        for i in fds:
            try:
                os.close(i.fd)
            except OSError:
                pass

    def main(self):
        if len(sys.argv) != 2:
            print("Invalid number of arguments", file=sys.stderr)
            sys.exit(errno.EINVAL)

        key = sys.argv[1]
        configure_logging(None, logging.DEBUG)

        self.datastore = get_datastore()
        self.configstore = ConfigStore(self.datastore)
        self.conn = Client()
        self.conn.connect('unix:')
        self.conn.login_service('task.{0}'.format(os.getpid()))
        self.conn.enable_server()
        self.conn.rpc.register_service_instance('taskproxy', self.service)
        self.conn.register_event_handler('task.progress', self.task_progress_handler)
        self.conn.call_sync('task.checkin', key)
        setproctitle.setproctitle('task executor (idle)')

        while True:
            try:
                task = self.task.get()
                logging.root.setLevel(self.conn.call_sync('management.get_logging_level'))
                setproctitle.setproctitle('task executor (tid {0})'.format(task['id']))

                if task['debugger']:
                    sys.path.append('/usr/local/lib/dispatcher/pydev')

                    import pydevd
                    host, port = task['debugger']
                    pydevd.settrace(host, port=port, stdoutToServer=True, stderrToServer=True)

                name, _ = os.path.splitext(os.path.basename(task['filename']))
                module = load_module_from_file(name, task['filename'])
                setproctitle.setproctitle('task executor (tid {0})'.format(task['id']))

                fds = list(self.collect_fds(task['args']))

                try:
                    self.instance = getattr(module, task['class'])(DispatcherWrapper(self.conn), self.datastore)
                    self.instance.configstore = self.configstore
                    self.instance.user = task['user']
                    self.instance.environment = task['environment']
                    self.running.set()
                    result = self.instance.run(*task['args'])
                except BaseException as err:
                    print("Task exception: {0}".format(str(err)), file=sys.stderr)
                    traceback.print_exc(file=sys.stderr)

                    if hasattr(self.instance, 'rollback'):
#.........这里部分代码省略.........
开发者ID:650elx,项目名称:middleware,代码行数:103,代码来源:main.py

示例15: Context

# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import connect [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


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