本文整理汇总了Python中freenas.dispatcher.client.Client.register_schema方法的典型用法代码示例。如果您正苦于以下问题:Python Client.register_schema方法的具体用法?Python Client.register_schema怎么用?Python Client.register_schema使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类freenas.dispatcher.client.Client
的用法示例。
在下文中一共展示了Client.register_schema方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Context
# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import register_schema [as 别名]
class Context(object):
def __init__(self):
self.logger = logging.getLogger('schedulerd')
self.config = None
self.datastore = None
self.configstore = None
self.client = None
self.scheduler = None
self.active_tasks = {}
def init_datastore(self):
try:
self.datastore = get_datastore(self.config)
except DatastoreException as err:
self.logger.error('Cannot initialize datastore: %s', str(err))
sys.exit(1)
self.configstore = ConfigStore(self.datastore)
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()
def init_scheduler(self):
store = MongoDBJobStore(database='freenas', collection='calendar_tasks', client=self.datastore.client)
self.scheduler = BackgroundScheduler(jobstores={'default': store}, timezone=pytz.utc)
self.scheduler.start()
def register_schemas(self):
self.client.register_schema('calendar-task', {
'type': 'object',
'additionalProperties': False,
'properties': {
'id': {'type': 'string'},
'name': {'type': 'string'},
'args': {'type': 'array'},
'description': {'type': 'string'},
'enabled': {'type': 'boolean'},
'hidden': {'type': 'boolean'},
'protected': {'type': 'boolean'},
'status': {'$ref': 'calendar-task-status'},
'schedule': {
'type': 'object',
'additionalProperties': False,
'properties': {
'coalesce': {'type': ['boolean', 'integer', 'null']},
'year': {'type': ['string', 'integer', 'null']},
'month': {'type': ['string', 'integer', 'null']},
'day': {'type': ['string', 'integer', 'null']},
'week': {'type': ['string', 'integer', 'null']},
'day_of_week': {'type': ['string', 'integer', 'null']},
'hour': {'type': ['string', 'integer', 'null']},
'minute': {'type': ['string', 'integer', 'null']},
'second': {'type': ['string', 'integer', 'null']},
'timezone': {'type': ['string', 'null']}
}
}
}
})
self.client.register_schema('calendar-task-status', {
'type': 'object',
'properties': {
'next_run_time': {'type': 'string'},
'last_run_status': {'type': 'string'},
'current_run_status': {'type': ['string', 'null']},
'current_run_progress': {'type': ['object', 'null']}
}
})
def connect(self):
while True:
try:
self.client.connect('unix:')
self.client.login_service('schedulerd')
self.client.enable_server()
self.client.register_service('scheduler.management', ManagementService(self))
self.client.register_service('scheduler.debug', DebugService())
self.client.resume_service('scheduler.management')
self.client.resume_service('scheduler.debug')
return
except (OSError, RpcException) as err:
self.logger.warning('Cannot connect to dispatcher: {0}, retrying in 1 second'.format(str(err)))
time.sleep(1)
def run_job(self, *args, **kwargs):
tid = self.client.submit_task(*args)
self.active_tasks[kwargs['id']] = tid
self.client.call_sync('task.wait', tid, timeout=None)
result = self.client.call_sync('task.status', tid)
if result['state'] != 'FINISHED':
try:
self.client.call_sync('alerts.emit', {
'name': 'scheduler.task.failed',
#.........这里部分代码省略.........
示例2: Main
# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import register_schema [as 别名]
#.........这里部分代码省略.........
self.connect()
self.client = Client()
self.client.on_error(on_error)
self.connect()
def init_server(self, address):
self.server = Server(self)
self.server.rpc = self.rpc
self.server.start(address)
thread = Thread(target=self.server.serve_forever)
thread.name = 'ServerThread'
thread.daemon = True
thread.start()
def parse_config(self, filename):
try:
with open(filename, 'r') as f:
self.config = json.load(f)
except IOError as err:
self.logger.error('Cannot read config file: %s', err.message)
sys.exit(1)
except ValueError:
self.logger.error('Config file has unreadable format (not valid JSON)')
sys.exit(1)
self.plugin_dirs = self.config['dscached']['plugin-dirs']
def connect(self):
while True:
try:
self.client.connect('unix:')
self.client.login_service('dscached')
self.client.enable_server(self.rpc)
self.client.resume_service('dscached.account')
self.client.resume_service('dscached.group')
self.client.resume_service('dscached.host')
self.client.resume_service('dscached.management')
self.client.resume_service('dscached.debug')
return
except (OSError, RpcException) as err:
self.logger.warning('Cannot connect to dispatcher: {0}, retrying in 1 second'.format(str(err)))
time.sleep(1)
def scan_plugins(self):
for i in self.plugin_dirs:
self.scan_plugin_dir(i)
def scan_plugin_dir(self, dir):
self.logger.debug('Scanning plugin directory %s', dir)
for f in os.listdir(dir):
name, ext = os.path.splitext(os.path.basename(f))
if ext != '.py':
continue
try:
plugin = imp.load_source(name, os.path.join(dir, f))
plugin._init(self)
except:
self.logger.error('Cannot initialize plugin {0}'.format(f), exc_info=True)
def register_plugin(self, name, cls):
self.plugins[name] = cls
self.logger.info('Registered plugin {0} (class {1})'.format(name, cls))
def register_schema(self, name, schema):
self.client.register_schema(name, schema)
def init_directories(self):
for i in self.datastore.query('directories'):
try:
directory = Directory(self, i)
directory.configure()
self.directories.append(directory)
except BaseException as err:
continue
def load_config(self):
self.search_order = self.configstore.get('directory.search_order')
self.cache_ttl = self.configstore.get('directory.cache_ttl')
self.cache_enumerations = self.configstore.get('directory.cache_enumerations')
self.cache_lookups = self.configstore.get('directory.cache_lookups')
def main(self):
parser = argparse.ArgumentParser()
parser.add_argument('-c', metavar='CONFIG', default=DEFAULT_CONFIGFILE, help='Middleware config file')
parser.add_argument('-s', metavar='SOCKET', default=DEFAULT_SOCKET_ADDRESS, help='Socket address to listen on')
args = parser.parse_args()
configure_logging('/var/log/dscached.log', 'DEBUG')
setproctitle.setproctitle('dscached')
self.config = args.c
self.parse_config(self.config)
self.init_datastore()
self.init_dispatcher()
self.load_config()
self.init_server(args.s)
self.scan_plugins()
self.init_directories()
self.client.wait_forever()
示例3: __init__
# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import register_schema [as 别名]
#.........这里部分代码省略.........
if not self.datastore.exists('network.interfaces', ('id', '=', i.name)):
self.logger.info('Found new interface {0} ({1})'.format(i.name, i.type.name))
self.datastore.insert('network.interfaces', {
'enabled': False,
'id': i.name,
'type': i.type.name,
'dhcp': False,
'noipv6': False,
'rtadv': False,
'mtu': None,
'media': None,
'aliases': []
})
# Remove unplugged NICs from DB
for i in self.datastore.query('network.interfaces', ('id', 'nin', existing), ('cloned', '=', False)):
self.datastore.delete('network.interfaces', i['id'])
def init_datastore(self):
try:
self.datastore = get_datastore(self.config)
except DatastoreException as err:
self.logger.error('Cannot initialize datastore: %s', str(err))
sys.exit(1)
self.configstore = ConfigStore(self.datastore)
def connect(self, resume=False):
while True:
try:
self.client.connect('unix:')
self.client.login_service('networkd')
self.client.enable_server()
self.register_schemas()
self.client.register_service('networkd.configuration', ConfigurationService(self))
self.client.register_service('networkd.debug', DebugService())
if resume:
self.client.resume_service('networkd.configuration')
self.client.resume_service('networkd.debug')
return
except (OSError, RpcException) as err:
self.logger.warning('Cannot connect to dispatcher: {0}, retrying in 1 second'.format(str(err)))
time.sleep(1)
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(resume=True)
self.client = Client()
self.client.on_error(on_error)
self.connect()
def init_routing_socket(self):
self.rtsock_thread = RoutingSocketEventSource(self)
self.rtsock_thread.start()
def register_schemas(self):
self.client.register_schema('network-aggregation-protocols', {
'type': 'string',
'enum': list(netif.AggregationProtocol.__members__.keys())
})
self.client.register_schema('network-interface-flags', {
示例4: Main
# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import register_schema [as 别名]
#.........这里部分代码省略.........
'type': i.type.name,
'dhcp': False,
'noipv6': False,
'rtadv': False,
'mtu': i.mtu,
'media': None,
'mediaopts': [],
'aliases': [],
'capabilities': {
'add': [],
'del': []
}
})
# Remove unplugged NICs from DB
for i in self.datastore.query('network.interfaces', ('id', 'nin', existing), ('cloned', '=', False)):
self.datastore.delete('network.interfaces', i['id'])
def init_datastore(self):
try:
self.datastore = get_datastore(self.config)
except DatastoreException as err:
self.logger.error('Cannot initialize datastore: %s', str(err))
sys.exit(1)
self.configstore = ConfigStore(self.datastore)
def connect(self, resume=False):
while True:
try:
self.client.connect('unix:')
self.client.login_service('networkd')
self.client.enable_server()
self.register_schemas()
self.client.register_service('networkd.configuration', ConfigurationService(self))
self.client.register_service('networkd.debug', DebugService())
if resume:
self.client.resume_service('networkd.configuration')
self.client.resume_service('networkd.debug')
return
except (OSError, RpcException) as err:
self.logger.warning('Cannot connect to dispatcher: {0}, retrying in 1 second'.format(str(err)))
time.sleep(1)
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(resume=True)
self.client = Client()
self.client.on_error(on_error)
self.connect()
def init_routing_socket(self):
self.rtsock_thread = RoutingSocketEventSource(self)
self.rtsock_thread.start()
def register_schemas(self):
self.client.register_schema('NetworkAggregationProtocols', {
'type': 'string',
'enum': list(netif.AggregationProtocol.__members__.keys())
})
self.client.register_schema('NetworkLaggPortFlags', {
示例5: __init__
# 需要导入模块: from freenas.dispatcher.client import Client [as 别名]
# 或者: from freenas.dispatcher.client.Client import register_schema [as 别名]
class Main:
def __init__(self):
self.config = None
self.client = None
self.datastore = None
self.configstore = None
self.rtsock_thread = None
self.logger = logging.getLogger('networkd')
def configure_dhcp(self, interface):
# Check if dhclient is running
if os.path.exists(os.path.join('/var/run', 'dhclient.{0}.pid'.format(interface))):
self.logger.info('Interface {0} already configured by DHCP'.format(interface))
return True
# XXX: start dhclient through launchd in the future
ret = subprocess.call(['/sbin/dhclient', interface])
return ret == 0
def interface_detached(self, name):
self.logger.warn('Interface {0} detached from the system'.format(name))
def interface_attached(self, name):
self.logger.warn('Interface {0} attached to the system'.format(name))
def using_dhcp_for_gateway(self):
for i in self.datastore.query('network.interfaces'):
if i.get('dhcp') and self.configstore.get('network.dhcp.assign_gateway'):
return True
return False
def scan_interfaces(self):
self.logger.info('Scanning available network interfaces...')
existing = []
# Add newly plugged NICs to DB
for i in list(netif.list_interfaces().values()):
# We want only physical NICs
if i.cloned:
continue
existing.append(i.name)
if not self.datastore.exists('network.interfaces', ('id', '=', i.name)):
self.logger.info('Found new interface {0} ({1})'.format(i.name, i.type.name))
self.datastore.insert('network.interfaces', {
'enabled': False,
'id': i.name,
'type': i.type.name
})
# Remove unplugged NICs from DB
for i in self.datastore.query('network.interfaces', ('id', 'nin', existing)):
self.datastore.delete('network.interfaces', i['id'])
def parse_config(self, filename):
try:
f = open(filename, 'r')
self.config = json.load(f)
f.close()
except IOError as err:
self.logger.error('Cannot read config file: %s', err.message)
sys.exit(1)
except ValueError as err:
self.logger.error('Config file has unreadable format (not valid JSON)')
sys.exit(1)
def init_datastore(self):
try:
self.datastore = get_datastore(self.config['datastore']['driver'], self.config['datastore']['dsn'])
except DatastoreException as err:
self.logger.error('Cannot initialize datastore: %s', str(err))
sys.exit(1)
self.configstore = ConfigStore(self.datastore)
def connect(self, resume=False):
while True:
try:
self.client.connect('127.0.0.1')
self.client.login_service('networkd')
self.client.enable_server()
self.register_schemas()
self.client.register_service('networkd.configuration', ConfigurationService(self))
self.client.register_service('networkd.debug', DebugService())
if resume:
self.client.resume_service('networkd.configuration')
self.client.resume_service('networkd.debug')
return
except socket.error as err:
self.logger.warning('Cannot connect to dispatcher: {0}, retrying in 1 second'.format(str(err)))
time.sleep(1)
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(resume=True)
#.........这里部分代码省略.........