本文整理汇总了Python中freenas.dispatcher.client.Client类的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process_request
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"'])
示例2: get_replication_client
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')
示例3: SyslogProvider
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)
示例4: main
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()
示例5: Context
class Context(object):
def __init__(self, *args, **kwargs):
self.client = None
self.entity_subscribers = {}
def start_entity_subscribers(self):
for i in ENTITY_SUBSCRIBERS:
if i in self.entity_subscribers:
self.entity_subscribers[i].stop()
del self.entity_subscribers[i]
e = EntitySubscriber(self.client, i)
e.start()
self.entity_subscribers[i] = e
def wait_entity_subscribers(self):
for i in self.entity_subscribers.values():
i.wait_ready()
def connect(self):
while True:
try:
self.client.connect("unix:")
self.client.login_service("collectd_{0}".format(PLUGIN_NAME))
# enable streaming responses as they are needed but entitysubscriber for
# reliable performace and such
self.client.call_sync("management.enable_features", ["streaming_responses"])
self.start_entity_subscribers()
self.wait_entity_subscribers()
return
except (OSError, RpcException) as err:
collectd.warning(
"{0} collectd plugin could not connect to server retrying in 5 seconds".format(PLUGIN_NAME)
)
time.sleep(5)
def connection_error(self, event, **kwargs):
if event in (ClientError.CONNECTION_CLOSED, ClientError.LOGOUT):
collectd.info("{0} collectd plugin connection to dispatcher lost".format(PLUGIN_NAME))
self.connect()
def init_dispatcher(self):
self.client = Client()
self.client.on_error(self.connection_error)
self.connect()
def disk_temps(self):
for disk in self.entity_subscribers["disk"].query(("status.smart_info.temperature", "!=", None)):
yield (disk["name"], disk["status"]["smart_info"]["temperature"])
示例6: connect_keepalive
def connect_keepalive(self):
while True:
try:
if not self.connection_id:
self.connection_id = uuid.uuid4()
self.msock.connect(SUPPORT_PROXY_ADDRESS)
self.logger.info("Connecting to {0}".format(SUPPORT_PROXY_ADDRESS))
self.rpc_fd = self.msock.create_channel(0)
time.sleep(1) # FIXME
self.client = Client()
self.client.connect("fd://", fobj=self.rpc_fd)
self.client.channel_serializer = MSockChannelSerializer(self.msock)
self.client.standalone_server = True
self.client.enable_server()
self.client.register_service("debug", DebugService(self))
self.client.call_sync(
"server.login", str(self.connection_id), socket.gethostname(), get_version(), "none"
)
self.set_state(ConnectionState.CONNECTED)
except BaseException as err:
self.logger.warning("Failed to initiate support connection: {0}".format(err), exc_info=True)
self.msock.disconnect()
else:
self.connected_at = datetime.now()
with self.cv:
self.cv.wait_for(lambda: self.state in (ConnectionState.LOST, ConnectionState.OFFLINE))
if self.state == ConnectionState.OFFLINE:
return
self.logger.warning("Support connection lost, retrying in 10 seconds")
time.sleep(10)
示例7: setUp
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
示例8: init_dispatcher
def init_dispatcher(self):
def on_error(reason, **kwargs):
if reason in (ClientError.CONNECTION_CLOSED, ClientError.LOGOUT):
self.logger.warning('Connection to dispatcher lost')
self.connect()
self.client = Client()
self.client.on_error(on_error)
self.connect()
示例9: setUp
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)
示例10: main
def main(self):
if len(sys.argv) != 2:
print("Invalid number of arguments", file=sys.stderr)
sys.exit(errno.EINVAL)
key = sys.argv[1]
logging.basicConfig(level=logging.DEBUG)
self.datastore = get_default_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.call_sync('task.checkin', key)
setproctitle.setproctitle('task executor (idle)')
while True:
try:
task = self.task.get()
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)
module = imp.load_source('plugin', task['filename'])
setproctitle.setproctitle('task executor (tid {0})'.format(task['id']))
try:
self.instance = getattr(module, task['class'])(DispatcherWrapper(self.conn), self.datastore)
self.instance.configstore = self.configstore
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)
self.put_status('FAILED', exception=err)
else:
self.put_status('FINISHED', result=result)
except RpcException as err:
print("RPC failed: {0}".format(str(err)), file=sys.stderr)
sys.exit(errno.EBADMSG)
except socket.error as err:
print("Cannot connect to dispatcher: {0}".format(str(err)), file=sys.stderr)
sys.exit(errno.ETIMEDOUT)
if task['debugger']:
import pydevd
pydevd.stoptrace()
setproctitle.setproctitle('task executor (idle)')
示例11: get_freenas_peer_client
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))
示例12: main
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()
示例13: __init__
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
示例14: __init__
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
self.msock = msock.client.Client()
self.msock.on_closed = self.on_msock_close
self.rpc_fd = -1
self.connection_id = None
self.jobs = []
self.state = ConnectionState.OFFLINE
self.config = None
self.keepalive = None
self.connected_at = None
self.cv = Condition()
self.rpc = RpcContext()
self.client = Client()
self.server = Server()
self.middleware_endpoint = None
示例15: LogdLogHandler
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()