def prune_orphaned_schedules(self): # remove schedules under /services/time/local/TIM that have no app manager = as_node('/services/time/local') if manager.has_child('TIM'): try: sh = as_node('/services/time/local/TIM') name_header = 'RZSched_' # create list of RZSched_'s under the TIM node schedules = filter( lambda k: k[:len(name_header)] == name_header, sh.children_names()) # compare appname after RZSched_, upto : with our children names orphans = filter( lambda k: k.split('_')[1].split(':')[0] not in self. children_names(), schedules) for o in orphans: try: sh.get_child(o).prune() msglog.log('Graphical Control:', 'pruned orphaned schedule: ', o) except: msglog.exception() if len(orphans): sh.save_schedule() except: msglog.exception()
def create_node(self, factory, nodeurl, **config): try: as_node(nodeurl) except KeyError: pass else: raise TypeError("Node exists: %s" % nodeurl) if isinstance(factory, str): module,sep,name = factory.rpartition(".") if name: exec("import %s" % module) factory = eval(factory) parent,sep,name = nodeurl.rpartition("/") configuration = {"name": name, "parent": parent} configuration.update(config) node = factory() try: node.configure(configuration) except: msglog.log("broadway", msglog.types.WARN, "Error prevented configuration of new node: %s" % node) msglog.exception(prefix="handled") try: node.prune() except: msglog.exception(prefix="handled") else: msglog.log("broadway", msglog.types.INFO, "Node successfully pruned.") else: msglog.log("broadway", msglog.types.INFO, "New node created: %s" % node) self.updatepdo(nodeurl, node) node.start() return node.configuration()
def start(self): self._do_read = getattr(self.parent, self.read_op) if self.write_op: self._do_write = getattr(self.parent, self.write_op) setattr(self, 'set', self._set) self.inparams_write = self.parent._proxy.methods[ self.write_op].inparams for parameter in self.write_params: if hasattr(self.__call_args_w, name): raise EConfigurationInvalid(name) if value.startswith('/') and is_node_url(value): setattr(self.__call_args_w, name, as_node(value)) else: setattr(self.__call_args_w, name, value) self.inparams_read = self.parent._proxy.methods[self.read_op].inparams for parameter in self.read_params: if not self.__call_args_r: self.__call_args_r = object() name = parameter['pn'] value = parameter['value'] if hasattr(self.__call_args_r, name): raise EConfigurationInvalid(name) if value.startswith('/') and is_node_url(value): setattr(self.__call_args_r, name, as_node(value)) else: setattr(self.__call_args_r, name, value) return super(RemoteWebServiceOp, self).start()
def start(self): self._do_read = getattr(self.parent, self.read_op) if self.write_op: self._do_write = getattr(self.parent, self.write_op) setattr(self, 'set', self._set) self.inparams_write = self.parent._proxy.methods[self.write_op].inparams for parameter in self.write_params: if hasattr(self.__call_args_w, name): raise EConfigurationInvalid(name) if value.startswith('/') and is_node_url(value): setattr(self.__call_args_w, name, as_node(value)) else: setattr(self.__call_args_w, name, value) self.inparams_read = self.parent._proxy.methods[self.read_op].inparams for parameter in self.read_params: if not self.__call_args_r: self.__call_args_r = object() name = parameter['pn'] value = parameter['value'] if hasattr(self.__call_args_r, name): raise EConfigurationInvalid(name) if value.startswith('/') and is_node_url(value): setattr(self.__call_args_r, name, as_node(value)) else: setattr(self.__call_args_r, name, value) return super(RemoteWebServiceOp, self).start()
def _setup_alarm_nodes(self): services = as_node('/services') if not services.has_child('External Alarms'): alarms_node = CompositeNode() alarms_node.configure({ 'name': 'External Alarms', 'parent': services }) alarms_node = as_node('/services/External Alarms') alarm_node = alarms.Manager() alarm_node.configure({'name': 'CPC Alarm', 'parent': alarms_node}) cpc_client_node = cpc_client.CpcClient(self._cpc_uhp_node) cpc_client_node.configure({ 'name': 'CPC Client', 'parent': alarm_node, 'node': '' }) ewebconnect_client_node = ewebconnect.EWebConnectAlarmClient() ewebconnect_client_node.configure({ 'name': 'eWebConnect Alarm Client', 'parent': alarm_node, 'host': '10.0.1.88', #'mother.envenergy.com', 'port': 16161, 'enabled': 1, }) alarms_node.start() return
def __init__(self, port1, port2): self.port1 = as_node('/interfaces/'+port1) self.port2 = as_node('/interfaces/'+port2) # it's just a helper class that is part of the Serial Tests super(_PortTester, self).__init__() self._test_name = 'SerialTester' return
def __init__(self, port1, port2): self.port1 = as_node('/interfaces/' + port1) self.port2 = as_node('/interfaces/' + port2) # it's just a helper class that is part of the Serial Tests super(_PortTester, self).__init__() self._test_name = 'SerialTester' return
def create_node(self, factory, nodeurl, **config): try: as_node(nodeurl) except KeyError: pass else: raise TypeError("Node exists: %s" % nodeurl) if isinstance(factory, str): module, sep, name = factory.rpartition(".") if name: exec("import %s" % module) factory = eval(factory) parent, sep, name = nodeurl.rpartition("/") configuration = {"name": name, "parent": parent} configuration.update(config) node = factory() try: node.configure(configuration) except: msglog.log("broadway", msglog.types.WARN, "Error prevented configuration of new node: %s" % node) msglog.exception(prefix="handled") try: node.prune() except: msglog.exception(prefix="handled") else: msglog.log("broadway", msglog.types.INFO, "Node successfully pruned.") else: msglog.log("broadway", msglog.types.INFO, "New node created: %s" % node) self.updatepdo(nodeurl, node) node.start() return node.configuration()
def start(self): self._subject = as_node(self.subject) if self.secured: self.security_manager = as_node('/services/Security Manager') self.user_service = self.security_manager.user_manager else: self.user_service = None self.security_manager = None self.user_manager = as_node("/services/User Manager") self._cloud_manager = as_node(self.cloud_manager) super(SyndicationViewer, self).start()
def start(self): self._subject = as_node(self.subject) if self.secured: self.security_manager = as_node("/services/Security Manager") self.user_service = self.security_manager.user_manager else: self.user_service = None self.security_manager = None self.user_manager = as_node("/services/User Manager") self._cloud_manager = as_node(self.cloud_manager) super(SyndicationViewer, self).start()
def _get_bcu_time( self ): if self.debug: print 'get bcu time' if self.bcu_time_node is None: self.bcu_time_node = as_node(self.bcu_time) #could test classes etc if self.bcu_date_node is None: self.bcu_date_node = as_node(self.bcu_date) y, m, d, dwk = self.bcu_date_node.get(1).value.value #should be date list hour, min, second, hundreths = self.bcu_time_node.get(1).value.value #should be time list answer = ((m, d, y), hour * 3600 + min * 60 + second) if self.debug: print 'bcu time', y, m, d, dwk, hour, min, second, hundreths return answer
def start(self): if self.is_running(): return if as_node('/services').has_child('Entity Manager'): em = as_node('/services/Entity Manager') if not em.is_running(): # see if this function is already wrapped. If it is wrapped # im_self is not an attribute. if hasattr(em.do_start, 'im_self'): em.do_start = wrapped(em.do_start, None, self.do_start) return self.do_start()
def __call__(self, local=False): if self.alarm is None: try: self.alarm = as_node(self.state['url']) except KeyError: self.alarm = self.state.get('class')() config = self.state['config'] parent = as_node(config['parent']) config.setdefault('nodespace', parent.nodespace) self.alarm.configure(config) self.alarm.start() return self.alarm
def start(self): self._alias_root = as_node('/aliases') # if the NBM supports BACnet, defer start up of entity infrastructure # until BACnet starts. for node in as_node('/services/network').children_nodes(): if isinstance(node, BACnet): if not node.is_running(): # see if this function is already wrapped. If it is wrapped # im_self is not an attribute. if hasattr(node.start, 'im_self'): node.start = wrapped(node.start, None, self.do_start) return self.do_start()
def __call__(self): if self.trigger is None: try: self.trigger = as_node(self.state['url']) except KeyError: self.trigger = self.state.get('class')() config = self.state['config'] parent = as_node(config['parent']) config.setdefault('nodespace', parent.nodespace) self.trigger.configure(config) if self.state['running']: self.trigger.start() for target in self.state.get('targets', []): self.trigger.add_target(target) return self.trigger
def start(self): self.debug_print(1, 'start()') if not self.running: self.running = 1 self.__status = -1 # Discover kids in start() rather than in configure, because # creating nodes in configure could conceivably confuse the # framework (ie should it attempt to config the new nodes?). # discover_children() explicitly configs each child node. #if self.discover: #self.discover_children() # Create/init thread that runs the whole shootin' match. Pass in # desired rznet_addr: if self.com_port_path in ( '/interfaces/com3', '/interfaces/com4', '/interfaces/com5', '/interfaces/com6', ): self.line_handler = RznetThread(as_node(self.com_port_path), self.rzhost_slave_port, None, 0, self.rznet_addr, self) self.connection_type = 'rs-485' else: #since it must be a rs-232 protocol, either local com port or virtual via tunnel.... self.line_handler = RzhostThread(as_node(self.com_port_path), self.rzhost_slave_port, self.rznet_addr, self) self.connection_type = 'rs-232' # applies to ALL devices self.line_handler.def_max_dev_subscrs = self.def_max_dev_subscrs #next, start the line handler thread self.line_handler.start() # opens RS485 file object, and slave and # cmd sockets # @fixme HACK to wait for the line_handler thread to init. self.line_handler._internal_lock.acquire() self.line_handler._internal_lock.release() # @fixme END HACK to wait for the line_handler thread to init. self.rznet_addr = self.line_handler.get_addrs()[ 0] # get actual addr from ldisc: self.debug_print(1, 'ldisc has addr %d.', self.rznet_addr) CompositeNode.start(self) self.line_handler.broadcast_update_request( ) #send this out AFTER all bound_proxies are started else: msglog.log('RznetNode', msglog.types.INFO, 'Allready started. Attempt to start any children') CompositeNode.start(self) return
def _discover_children(self, force=0, **options): #search through bacnet devices for Schedule Objects #discover_mode: 0==none, 1==use numbers, 2==use name properties, 3==use both if self.discover_mode != 'never' and self.running == 1: # and self._been_discovered == 0: try: schedule_group = as_node(self.device_link).get_child('17') #since bacnet object groups do not agressively discover #children instances, this will force full discovery schedule_group._discover_children(1) #forced discovery schedules = schedule_group.children_nodes( ) #auto_discover=(self.discover_mode != 'never')) #schedules # add Calendar Objects as Schedules calendar_group = as_node(self.device_link).get_child('6') #since bacnet object groups do not agressively discover #children instances, this will force full discovery calendar_group._discover_children(1) #forced discovery schedules.extend(calendar_group.children_nodes( )) #auto_discover=(self.discover_mode != 'never')) #schedules # filter out any existing nodes existing = [ as_node(c.link) for c in self.children_nodes(auto_discover=0) ] existing += [ as_node(c.link) for c in self._nascent_children.values() ] schedules = filter(lambda d: d not in existing, schedules) #filter out any existing nodes for s in schedules: name = s.name #default name will be the schedule ID if self.discover_mode[: 4] == 'name': #then we want name of schedule try: name = str(s.get_child('77').get()) if self.discover_mode == 'name_and_numeric': #use both ID and name name += ' (' + s.name + ')' except: pass #if name is not available, use ID only sr = Scheduler() sr.link = s.as_node_url( ) #url of bacnet schedule object node sr.source = self.source self._nascent_children['RZSched_' + name] = sr #self._been_discovered = 1 #disabled to allow new objects to be discovered except ENoSuchName, e: if debug: msglog.exception() pass except:
def __call__(self): if self.exporter is None: try: self.exporter = as_node(self.state['url']) except KeyError: self.exporter = self.state.get('class')() config = self.state['config'] parent = as_node(config['parent']) config.setdefault('nodespace', parent.nodespace) self.exporter.configure(config) self.exporter.start() for source, args in self.state.get('sources', {}).items(): try: self.exporter.add_source(source, *args) except: msglog.exception() return self.exporter
def __node_from_components(klass, components): elements = ['/'] parent = as_node('/') for element, factory in components: elements.append(urllib.quote(element)) path = os.path.join(*elements) if node_exists(path): parent = as_node(path) continue msglog.log('Device Manager', msglog.types.INFO, "Creating %r." % path) node = factory() node.configure({'parent':parent,'name':element}) parent = node return parent
def __call__(self, local=False): if self.alarm is None: try: self.alarm = as_node(self.state['url']) except KeyError: self.alarm = self.state.get('class')() config = self.state['config'] parent = as_node(config['parent']) config.setdefault('nodespace', parent.nodespace) self.alarm.configure(config) self.alarm.start() events = [IPickles(evt)(local) for evt in self.state['events']] msglog.log('broadway', msglog.types.WARN, 'Deprecated AlarmPickler used to unpickle %s.' % self.alarm.name) return self.alarm
def get(self): try: node = as_node(self.nodeurl) except ENoSuchName: return '' else: return node.attributes.get(self.attribute, '')
def handle_request(self, request): request._DynamicLogHandler__success = False path = request.get_path() if request.has_query(): query = request.get_query_dictionary() log_name = "" if (query.has_key('node_url')): log_name = query['node_url'] else: if path[-1] == '/': path = path[0:-1] log_name = path[len(self.request_path):] log_name = os.path.join('/services/logger', log_name) #use as_node to follow Aliases log_node = as_node(log_name) if (query.has_key('action')): action = query['action'] if action == 'download_all': self.download_all(request, log_node, query) elif action == 'download_slice': self.download_slice(request, log_node, query) elif action == 'download_sequence': self.download_sequence(request, log_node, query) if not request._DynamicLogHandler__success: raise EInternalError('Failed to handle request.') return
def __init__(self, nrt): self.events = 0 self.debug = False self.exceptions = 0 self.lookup = dict([(nid, as_node(nodeurl)) for nid, nodeurl in nrt.items()]) super(Target, self).__init__()
def clear_subscr(self, targets=None): if self.line_handler is None: return if (type(targets) == types.ListType): targets0_type = type(targets[0]) if (targets0_type == types.TupleType): pass elif (targets0_type == types.StringType): new_targets = [] for node_URL in targets: node = None try: node = as_node(node_URL) except ENoSuchName: msglog.exception() continue new_targets.append((node.lan_address,node.id_number,)) if len(new_targets) == 0: return targets = new_targets else: raise EInvalidValue('targets',targets,'Should be None, int, ' \ 'or list of 2-tuples (dev_id, obj_id) or ' \ 'a list of node URL strings.') self.line_handler.clear_subscr(targets) return
def execute(self, *args): target = as_node(self._target) try: self._last_value = target.get_override_at(self._priority_level) target.release(self._priority_level) # undo not possible except: pass
def start(self): if self.__running: return if self.debug: msglog.log('EnergywiseManager :', msglog.types.INFO, 'Inside start' ) CompositeNode.start(self) # start_node = as_node('/services/EnergywiseManager/') # self.configure_trend_in_switches(start_node, 60) self.__running = True self._pdo_lock.acquire() self._pdo = PersistentDataObject(self, dmtype=GC_NEVER) self._pdo.trends = {} self._pdo.load() self._pdo_lock.release() if self.has_child('trends'): self.trends = self.get_child('trends') else: self.trends = CompositeNode() self.trends.configure({'parent':self, 'name':'trends'}) self.trends.start() # start trending for saved domains for domain,freq in self._pdo.trends.items(): try: start_node = as_node(domain) # self.configure_trend_in_switches( start_node,freq ) start_node.new_trend(freq) except: self.delete_trend_configuration(domain) return
def start(self): Column.start(self) if (type(self.__function_config) == types.StringType and string.count(self.__function_config,'as_node') == 1 and self.__function_config.endswith('get')): func = self.__function_config self.__node = as_node(func[func.find('(')+2:func.rfind(')')-1]) if self.use_subscription_manager: self._sid = SM.create_delivered(self, {1:as_node_url(self.__node)}) self.function = self.get_last else: self.function = getattr(self.__node,func[func.rfind('.')+1:]) rexec = self.parent.parent.get_environment() self.original_function = RFunction(self.function, args=self.args, context=self.context, rexec=rexec) self.function = self._convert self.variables = {} nodes = self.children_nodes() for potential_calculator in nodes: if hasattr(potential_calculator, 'evaluate'): if self._calculator: #oops raise EAttributeError('Too many calculator nodes', self) self._calculator = potential_calculator self.function = self._evaluate # hook the calculator in self.__original_function = self.original_function self.original_function = self.__evaluate_original_function self.__started = 1
def __init__(self, nrt): self.events = 0 self.debug = False self.exceptions = 0 self.lookup = dict([(nid, as_node(nodeurl)) for nid,nodeurl in nrt.items()]) super(Target, self).__init__()
def get_subject(self): if self.__subject is None: if self.is_remote(): self.set_subject(as_node(self.as_remote_url())) else: self.set_subject(self) return self.__subject
def configure(self, config): set_attribute(self, 'debug', 0, config, int) set_attribute(self, 'ip', '', config) default = '${mpx.properties.%s_PORT}' % self.server_type set_attribute(self, 'port', default, config, int) set_attribute(self, 'user_manager', as_node('/services/User Manager'), config, as_node) set_attribute(self, 'authentication', 'form', config) if (self.authentication is not None and self.authentication not in ('digest', 'basic', 'form')): raise EInvalidValue('authentication', self.authentication, 'Authentication scheme not recognized.') set_attribute(self, 'port', default, config, int) set_attribute(self, 'maintenance_interval', 25, config, int) set_attribute(self, 'zombie_timeout', 600, config, int) set_attribute(self, 'thread_count', 3, config, int) if not self.has_child("Request Responder"): self._setup_request_responder() if not self.has_child("Authenticator"): self._setup_authentication_handler() if not self.has_child("PSP Handler"): self._setup_psp_handler() if not self.has_child("JSON-RPC Handler"): self._setup_json_handler() ServiceNode.configure(self, config)
def create_logger_alias(self, parent, name): logger_service = as_internal_node('/services/logger') if logger_service.has_child(name): # get_child returns the actual child, as_node would follow an # alias. trend_alias = logger_service.get_child(name) name_in_use = not isinstance(trend_alias, Alias) if not name_in_use: name_in_use |= as_internal_node( os.path.dirname(trend_alias.node_url)) is not self if name_in_use: raise ENameInUse(trend_alias.as_node_url()) else: trend_alias = Alias() parent_url = as_node(parent).as_node_url() quoted_name = urllib.quote(name, '') trend_alias.configure({ 'name': name, 'parent': logger_service, 'node_url': os.path.join(parent_url, quoted_name, quoted_name) }) return
def start(self): RequestHandler.start(self) self.WEB_ROOT = properties.HTTP_ROOT if self.parent.server_type == 'HTTPS': self.WEB_ROOT = properties.HTTPS_ROOT for handler in self.parent.children_nodes(): if isinstance(handler, FileSpace): self.filespace = handler break err_message = 'PSP handler not running in secured mode because \ no %s was found. Config parameter "secured" \ being overriden to False' if self.secured and self.filespace: try: sm = as_node('/services/Security Manager') except KeyError: msglog.log('broadway', msglog.types.WARN, err_message % 'Security Manager') msglog.exception(prefix = 'Handled') self.provides_security = self._secured = False else: self.security_manager = sm self.provides_security = self._secured = True else: if self.secured: # not secured because we could not locate filespace object. msglog.log('broadway', msglog.types.WARN, err_message % 'FileSpace manager') self.provides_security = self._secured = False
def handle_request(self, request): response = Response(request) request_data = request.get_post_data_as_dictionary() request_data.update(request.get_query_string_as_dictionary()) if not (request_data.has_key('type') and request_data.has_key('id') and request_data.has_key('method')): response.error(400, 'Missnig required param type, id, or method.') return id = urllib.unquote_plus(request_data.get('id')[0]) if request_data.get('type')[0] == 'node': target = as_node(id) elif request_data.get('type')[0] == 'event': target = Event.get_event(id) else: response.error(400, 'Unknown type.') return methodname = urllib.unquote_plus(request_data.get('method')[0]) method = getattr(target, methodname) args = urllib.unquote_plus(request_data.get('args', ['()'])[0]) args = eval(args) keywords = urllib.unquote_plus(request_data.get('keywords', ['{}'])[0]) keywords = eval(keywords) result = method(*args, **keywords) result = repr(result) self.message('Invoking %s on %s with %s, %s, returned %s' % (methodname, id, args, keywords, result)) response.send(result)
def save_trends(self, trend_list): # Traverse through _pdo.items and check if new domain is either subset # of any configured or superset. # If subset return with msg already covered and dont save this # If superset then configure new ones and delete subset from # _pdo.items '''Adding and saving trends''' for point in reversed(trend_list): point_period = point['frequency'] point_domain = point['domain'] for saved_domain,saved_period in tuple(self._pdo.trends.items()): if saved_domain == point_domain: if saved_period != point_period: self.delete_trend_configuration(saved_domain) break if not self._pdo.trends.has_key(point_domain): # add this trend try: domain_node = as_node(point_domain) if isinstance(domain_node,EnergywiseSwitch) or isinstance(domain_node,EnergywiseDomain): self.add_trend_configuration(point_period, point_domain) domain_node.new_trend(point_period) except Exception: msglog.exception() msglog.log( "Energywise",msglog.types.ERR, "Failed to create trend for %r every %r seconds" %(point_domain,point_period) ) return
def move_sched(self, source, destination, cfg, is_rename=False): source = normalize_nodepath(source) destination = normalize_nodepath(destination) for sched in self.get_scheds(): if not sched.startswith(source): continue data = self._persisted_data[sched] del self._persisted_data[sched] if sched == source: # rename if is_rename: newsched = destination else: newsched = sched.replace( source, destination) + source.split('/')[-2] + '/' oldroot = sched newroot = newsched self._persisted_data[newsched] = data # prior to persisting, the schedule should have been moved # within the nodetree. We grab and persist the latest configuration. # This put call will also ensure sync to disk to takes place. self.put_sched_cfg(newsched, cfg) else: newsched = normalize_nodepath(sched.replace( oldroot, newroot)) #+ sched_name + '/' self._persisted_data[newsched] = data self.put_sched_cfg(newsched, serialize_node(as_node(newsched)))
def create_partition_tree(name, mount_point): global storage_root_url children_names = ['available', 'size', 'used', ] msgstr = 'In create_drive_tree with name of %s ' % name msgstr += 'and mount_point of %s.' % mount_point msglog.log('Services_Storage', msglog.types.INFO, msgstr) pnode = as_node(storage_root_url) dict = {'name':name, 'mount_point':mount_point, 'debug':1, 'parent':pnode, } drive_node = DriveNode() drive_node.configure(dict) # for x in children_names: dict = {'name':x, 'debug':1, 'parent':drive_node, } drive_attr_node = DriveAttributeNode() drive_attr_node.configure(dict) # drive_node.start()
def start(self): super(Kwh2Kw, self).start() self.running = True self._history = KwList(self._window_size) self._sid = SM.create_polled({self._nid:self.link}) # retrieve an initial value to start things off value = ts = None result = SM.poll_all(self._sid) if result is None: # still waiting try: value = as_node(self.link).get() ts = time.time() except: pass else: try: value = result[self._nid]['value'] ts = result[self._nid]['timestamp'] except: pass if isinstance(value, MpxException): value = None if value and ts: self._history.add(value, ts) self._scheduled = scheduler.seconds_from_now_do(self.sample_period, self.run_update) return
def get(self, skipCache=0): if self.connection_type == 'rs-485': if self.__status: status_str = 'passive' addrs = self.line_handler.get_addrs() if addrs[0] != addrs[ 1]: # if our and next addrs differ, then we're passing token status_str = 'active' return status_str if self.__status is None: return 'not started' if self.__status == -1: return 'error during startup' return 'license not found' if self.__status: #started try: if as_node(self.com_port_path).is_connected(): return 'connected' else: return 'not connected' except: pass return 'started' if self.__status is None: return 'not started' if self.__status == -1: return 'error during startup' return 'license not found'
def clear_subscr(self, targets=None): if self.line_handler is None: return if (type(targets) == types.ListType): targets0_type = type(targets[0]) if (targets0_type == types.TupleType): pass elif (targets0_type == types.StringType): new_targets = [] for node_URL in targets: node = None try: node = as_node(node_URL) except ENoSuchName: msglog.exception() continue new_targets.append(( node.lan_address, node.id_number, )) if len(new_targets) == 0: return targets = new_targets else: raise EInvalidValue('targets',targets,'Should be None, int, ' \ 'or list of 2-tuples (dev_id, obj_id) or ' \ 'a list of node URL strings.') self.line_handler.clear_subscr(targets) return
def start(self): super(Kwh2Kw, self).start() self.running = True self._history = KwList(self._window_size) self._sid = SM.create_polled({self._nid: self.link}) # retrieve an initial value to start things off value = ts = None result = SM.poll_all(self._sid) if result is None: # still waiting try: value = as_node(self.link).get() ts = time.time() except: pass else: try: value = result[self._nid]['value'] ts = result[self._nid]['timestamp'] except: pass if isinstance(value, MpxException): value = None if value and ts: self._history.add(value, ts) self._scheduled = scheduler.seconds_from_now_do( self.sample_period, self.run_update) return
def handle_request(self, request): response = Response(request) request_data = request.get_post_data_as_dictionary() request_data.update(request.get_query_string_as_dictionary()) if not (request_data.has_key('type') and request_data.has_key('id') and request_data.has_key('method')): response.error(400, 'Missnig required param type, id, or method.') return id = urllib.unquote_plus(request_data.get('id')[0]) if request_data.get('type')[0] == 'node': target = as_node(id) elif request_data.get('type')[0] == 'event': target = Event.get_event(id) else: response.error(400, 'Unknown type.') return methodname = urllib.unquote_plus(request_data.get('method')[0]) method = getattr(target, methodname) args = urllib.unquote_plus(request_data.get('args', ['()'])[0]) args = eval(args) keywords = urllib.unquote_plus(request_data.get('keywords', ['{}'])[0]) keywords = eval(keywords) result = method(*args, **keywords) result = repr(result) self.message('Invoking %s on %s with %s, %s, returned %s' % ( methodname, id, args, keywords, result)) response.send(result)
def configure(self, config): set_attribute(self, 'debug', 0, config, int) set_attribute(self, 'ip', '', config) default = '${mpx.properties.%s_PORT}' % self.server_type set_attribute(self,'port',default,config,int) set_attribute(self,'user_manager', as_node('/services/User Manager'),config,as_node) set_attribute(self,'authentication','form',config) if (self.authentication is not None and self.authentication not in ('digest','basic','form')): raise EInvalidValue('authentication',self.authentication, 'Authentication scheme not recognized.') set_attribute(self,'port',default,config,int) set_attribute(self, 'maintenance_interval', 25, config, int) set_attribute(self, 'zombie_timeout', 600, config, int) set_attribute(self, 'thread_count', 3, config, int) if not self.has_child("Request Responder"): self._setup_request_responder() if not self.has_child("Authenticator"): self._setup_authentication_handler() if not self.has_child("PSP Handler"): self._setup_psp_handler() if not self.has_child("JSON-RPC Handler"): self._setup_json_handler() ServiceNode.configure(self, config)
def save_trends(self, trend_list): # Traverse through _pdo.items and check if new domain is either subset # of any configured or superset. # If subset return with msg already covered and dont save this # If superset then configure new ones and delete subset from # _pdo.items '''Adding and saving trends''' for point in reversed(trend_list): point_period = point['frequency'] point_domain = point['domain'] for saved_domain, saved_period in tuple(self._pdo.trends.items()): if saved_domain == point_domain: if saved_period != point_period: self.delete_trend_configuration(saved_domain) break if not self._pdo.trends.has_key(point_domain): # add this trend try: domain_node = as_node(point_domain) if isinstance(domain_node, EnergywiseSwitch) or isinstance( domain_node, EnergywiseDomain): self.add_trend_configuration(point_period, point_domain) domain_node.new_trend(point_period) except Exception: msglog.exception() msglog.log( "Energywise", msglog.types.ERR, "Failed to create trend for %r every %r seconds" % (point_domain, point_period)) return
def move_sched(self, source, destination, cfg, is_rename=False): source = normalize_nodepath(source) destination = normalize_nodepath(destination) for sched in self.get_scheds(): if not sched.startswith(source): continue data = self._persisted_data[sched] del self._persisted_data[sched] if sched == source: # rename if is_rename: newsched = destination else: newsched = sched.replace(source, destination) + source.split('/')[-2] + '/' oldroot = sched newroot = newsched self._persisted_data[newsched] = data # prior to persisting, the schedule should have been moved # within the nodetree. We grab and persist the latest configuration. # This put call will also ensure sync to disk to takes place. self.put_sched_cfg(newsched, cfg) else: newsched = normalize_nodepath(sched.replace(oldroot, newroot)) #+ sched_name + '/' self._persisted_data[newsched] = data self.put_sched_cfg(newsched, serialize_node(as_node(newsched)))
def _setup_trigger(self): try: self._sid = SM.create_delivered(self, {1:as_node(self.trigger)}) except ENotStarted, ENoSuchNode: msg = 'TriggeredExporter trigger: %s does not exist - could be nascent' % self._trigger msglog.log('broadway',msglog.types.WARN,msg) scheduler.seconds_from_now_do(60, self._setup_trigger)
def handle_request(self, request): nodeurl = request.get_path()[len(self.request_path):] node = as_node(nodeurl) generator = listurls(node) generated = GeneratedList(generator) request.push(lineproducer(generated)) request.done()
def discover_by_type(self, entity_path, purposes): if not entity_path.startswith(EM): entity_path = EM + entity_path matches = self.qm.fetch( {"query": {"name": "*"}, "properties": {"purpose":purposes}} ).get('items') result = {} for property_url in matches: try: prop_ref = as_node(property_url) entity_path = as_entity_url(prop_ref.entity) if not result.has_key(entity_path): result[entity_path] = {} prop_id = [prop_ref.type, prop_ref.name] for purpose in prop_ref.get_meta_values('purpose'): if purpose in purposes: if result[entity_path].has_key(purpose): result[entity_path][purpose].append(prop_id) else: result[entity_path][purpose] = [prop_id] except: message = 'Error adding value to discover_by_type result set' msglog.log('Global Setpoint Manager', msglog.types.INFO, message) msglog.exception() return result
def __init__(self): ## Register method to handle Null types xmlrpclib.Marshaller.dispatch[types.NoneType] = dump_None self._root_node = as_node('/') self._security_manager = None self._secured = False super(RNA, self).__init__()
def start(self): Column.start(self) if (type(self.__function_config) == types.StringType and string.count(self.__function_config, 'as_node') == 1 and self.__function_config.endswith('get')): func = self.__function_config self.__node = as_node(func[func.find('(') + 2:func.rfind(')') - 1]) if self.use_subscription_manager: self._sid = SM.create_delivered(self, {1: as_node_url(self.__node)}) self.function = self.get_last else: self.function = getattr(self.__node, func[func.rfind('.') + 1:]) rexec = self.parent.parent.get_environment() self.original_function = RFunction(self.function, args=self.args, context=self.context, rexec=rexec) self.function = self._convert self.variables = {} nodes = self.children_nodes() for potential_calculator in nodes: if hasattr(potential_calculator, 'evaluate'): if self._calculator: #oops raise EAttributeError('Too many calculator nodes', self) self._calculator = potential_calculator self.function = self._evaluate # hook the calculator in self.__original_function = self.original_function self.original_function = self.__evaluate_original_function self.__started = 1
def start(self): if self.__running: return if self.debug: msglog.log('EnergywiseManager :', msglog.types.INFO, 'Inside start') CompositeNode.start(self) # start_node = as_node('/services/EnergywiseManager/') # self.configure_trend_in_switches(start_node, 60) self.__running = True self._pdo_lock.acquire() self._pdo = PersistentDataObject(self, dmtype=GC_NEVER) self._pdo.trends = {} self._pdo.load() self._pdo_lock.release() if self.has_child('trends'): self.trends = self.get_child('trends') else: self.trends = CompositeNode() self.trends.configure({'parent': self, 'name': 'trends'}) self.trends.start() # start trending for saved domains for domain, freq in self._pdo.trends.items(): try: start_node = as_node(domain) # self.configure_trend_in_switches( start_node,freq ) start_node.new_trend(freq) except: self.delete_trend_configuration(domain) return