idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
19,600 | def get_new_broks ( self ) : for satellites in [ self . schedulers , self . pollers , self . reactionners , self . receivers ] : for satellite_link in list ( satellites . values ( ) ) : logger . debug ( "Getting broks from %s" , satellite_link ) _t0 = time . time ( ) try : tmp_broks = satellite_link . get_broks ( self . name ) except LinkError : logger . warning ( "Daemon %s connection failed, I could not get the broks!" , satellite_link ) else : if tmp_broks : logger . debug ( "Got %d Broks from %s in %s" , len ( tmp_broks ) , satellite_link . name , time . time ( ) - _t0 ) statsmgr . gauge ( 'get-new-broks-count.%s' % ( satellite_link . name ) , len ( tmp_broks ) ) statsmgr . timer ( 'get-new-broks-time.%s' % ( satellite_link . name ) , time . time ( ) - _t0 ) for brok in tmp_broks : brok . instance_id = satellite_link . instance_id # Add the broks to our global list self . external_broks . extend ( tmp_broks ) | Get new broks from our satellites | 295 | 7 |
19,601 | def add_group_members ( self , members ) : if not isinstance ( members , list ) : members = [ members ] if not getattr ( self , 'group_members' , None ) : self . group_members = members else : self . group_members . extend ( members ) | Add a new group member to the groups list | 62 | 9 |
19,602 | def get_realms_by_explosion ( self , realms ) : # If rec_tag is already set, then we detected a loop in the realms hierarchy! if getattr ( self , 'rec_tag' , False ) : self . add_error ( "Error: there is a loop in the realm definition %s" % self . get_name ( ) ) return None # Ok, not in a loop, we tag the realm and parse its members self . rec_tag = True # Order realm members list by name self . realm_members = sorted ( self . realm_members ) for member in self . realm_members : realm = realms . find_by_name ( member ) if not realm : self . add_unknown_members ( member ) continue children = realm . get_realms_by_explosion ( realms ) if children is None : # We got a loop in our children definition self . all_sub_members = [ ] self . realm_members = [ ] return None # Return the list of all unique members return self . all_sub_members | Get all members of this realm including members of sub - realms on multi - levels | 227 | 16 |
19,603 | def set_level ( self , level , realms ) : self . level = level if not self . level : logger . info ( "- %s" , self . get_name ( ) ) else : logger . info ( " %s %s" , '+' * self . level , self . get_name ( ) ) self . all_sub_members = [ ] self . all_sub_members_names = [ ] for child in sorted ( self . realm_members ) : child = realms . find_by_name ( child ) if not child : continue self . all_sub_members . append ( child . uuid ) self . all_sub_members_names . append ( child . get_name ( ) ) grand_children = child . set_level ( self . level + 1 , realms ) for grand_child in grand_children : if grand_child in self . all_sub_members_names : continue grand_child = realms . find_by_name ( grand_child ) if grand_child : self . all_sub_members_names . append ( grand_child . get_name ( ) ) self . all_sub_members . append ( grand_child . uuid ) return self . all_sub_members_names | Set the realm level in the realms hierarchy | 268 | 8 |
19,604 | def get_all_subs_satellites_by_type ( self , sat_type , realms ) : res = copy . copy ( getattr ( self , sat_type ) ) for member in self . all_sub_members : res . extend ( realms [ member ] . get_all_subs_satellites_by_type ( sat_type , realms ) ) return res | Get all satellites of the wanted type in this realm recursively | 85 | 13 |
19,605 | def get_links_for_a_broker ( self , pollers , reactionners , receivers , realms , manage_sub_realms = False ) : # Create void satellite links cfg = { 'pollers' : { } , 'reactionners' : { } , 'receivers' : { } , } # Our self.daemons are only identifiers... that we use to fill the satellite links for poller_id in self . pollers : poller = pollers [ poller_id ] cfg [ 'pollers' ] [ poller . uuid ] = poller . give_satellite_cfg ( ) for reactionner_id in self . reactionners : reactionner = reactionners [ reactionner_id ] cfg [ 'reactionners' ] [ reactionner . uuid ] = reactionner . give_satellite_cfg ( ) for receiver_id in self . receivers : receiver = receivers [ receiver_id ] cfg [ 'receivers' ] [ receiver . uuid ] = receiver . give_satellite_cfg ( ) # If the broker manages sub realms, fill the satellite links... if manage_sub_realms : # Now pollers for poller_id in self . get_all_subs_satellites_by_type ( 'pollers' , realms ) : poller = pollers [ poller_id ] cfg [ 'pollers' ] [ poller . uuid ] = poller . give_satellite_cfg ( ) # Now reactionners for reactionner_id in self . get_all_subs_satellites_by_type ( 'reactionners' , realms ) : reactionner = reactionners [ reactionner_id ] cfg [ 'reactionners' ] [ reactionner . uuid ] = reactionner . give_satellite_cfg ( ) # Now receivers for receiver_id in self . get_all_subs_satellites_by_type ( 'receivers' , realms ) : receiver = receivers [ receiver_id ] cfg [ 'receivers' ] [ receiver . uuid ] = receiver . give_satellite_cfg ( ) return cfg | Get a configuration dictionary with pollers reactionners and receivers links for a broker | 471 | 15 |
19,606 | def get_links_for_a_scheduler ( self , pollers , reactionners , brokers ) : # Create void satellite links cfg = { 'pollers' : { } , 'reactionners' : { } , 'brokers' : { } , } # Our self.daemons are only identifiers... that we use to fill the satellite links try : for poller in self . pollers + self . get_potential_satellites_by_type ( pollers , "poller" ) : if poller in pollers : poller = pollers [ poller ] cfg [ 'pollers' ] [ poller . uuid ] = poller . give_satellite_cfg ( ) for reactionner in self . reactionners + self . get_potential_satellites_by_type ( reactionners , "reactionner" ) : if reactionner in reactionners : reactionner = reactionners [ reactionner ] cfg [ 'reactionners' ] [ reactionner . uuid ] = reactionner . give_satellite_cfg ( ) for broker in self . brokers + self . get_potential_satellites_by_type ( brokers , "broker" ) : if broker in brokers : broker = brokers [ broker ] cfg [ 'brokers' ] [ broker . uuid ] = broker . give_satellite_cfg ( ) except Exception as exp : # pylint: disable=broad-except logger . exception ( "realm.get_links_for_a_scheduler: %s" , exp ) # for poller in self.get_potential_satellites_by_type(pollers, "poller"): # logger.info("Poller: %s", poller) # cfg['pollers'][poller.uuid] = poller.give_satellite_cfg() # # for reactionner in self.get_potential_satellites_by_type(reactionners, "reactionner"): # cfg['reactionners'][reactionner.uuid] = reactionner.give_satellite_cfg() # # for broker in self.get_potential_satellites_by_type(brokers, "broker"): # cfg['brokers'][broker.uuid] = broker.give_satellite_cfg() return cfg | Get a configuration dictionary with pollers reactionners and brokers links for a scheduler | 521 | 16 |
19,607 | def explode ( self ) : # Manage higher realms where defined for realm in [ tmp_realm for tmp_realm in self if tmp_realm . higher_realms ] : for parent in realm . higher_realms : higher_realm = self . find_by_name ( parent ) if higher_realm : # Add the realm to its parent realm members higher_realm . realm_members . append ( realm . get_name ( ) ) for realm in self : # Set a recursion tag to protect against loop for tmp_realm in self : tmp_realm . rec_tag = False realm . get_realms_by_explosion ( self ) # Clean the recursion tag for tmp_realm in self : del tmp_realm . rec_tag | Explode realms with each realm_members and higher_realms to get all the realms sub realms . | 169 | 21 |
19,608 | def get_default ( self , check = False ) : found = [ ] for realm in sorted ( self , key = lambda r : r . level ) : if getattr ( realm , 'default' , False ) : found . append ( realm ) if not found : # Retain as default realm the first realm in name alphabetical order found_names = sorted ( [ r . get_name ( ) for r in self ] ) if not found_names : self . add_error ( "No realm is defined in this configuration! " "This should not be possible!" ) return None default_realm_name = found_names [ 0 ] default_realm = self . find_by_name ( default_realm_name ) default_realm . default = True found . append ( default_realm ) if check : self . add_error ( "No realm is defined as the default one! " "I set %s as the default realm" % default_realm_name ) default_realm = found [ 0 ] if len ( found ) > 1 : # Retain as default realm the first so-called default realms in name alphabetical order found_names = sorted ( [ r . get_name ( ) for r in found ] ) default_realm_name = found_names [ 0 ] default_realm = self . find_by_name ( default_realm_name ) # Set all found realms as non-default realms for realm in found : if realm . get_name ( ) != default_realm_name : realm . default = False if check : self . add_warning ( "More than one realm is defined as the default one: %s. " "I set %s as the default realm." % ( ',' . join ( found_names ) , default_realm_name ) ) self . default = default_realm return default_realm | Get the default realm | 402 | 4 |
19,609 | def reload_configuration ( self ) : # If I'm not the master arbiter, ignore the command and raise a log if not self . app . is_master : message = u"I received a request to reload the monitored configuration. " u"I am not the Master arbiter, I ignore and continue to run." logger . warning ( message ) return { '_status' : u'ERR' , '_message' : message } message = "I received a request to reload the monitored configuration" if self . app . loading_configuration : message = message + "and I am still reloading the monitored configuration ;)" else : self . app . need_config_reload = True logger . warning ( message ) return { '_status' : u'OK' , '_message' : message } | Ask to the arbiter to reload the monitored configuration | 172 | 10 |
19,610 | def command ( self , command = None , timestamp = None , element = None , host = None , service = None , user = None , parameters = None ) : # pylint: disable=too-many-branches if cherrypy . request . method in [ "POST" ] : if not cherrypy . request . json : return { '_status' : u'ERR' , '_message' : u'You must POST parameters on this endpoint.' } if command is None : try : command = cherrypy . request . json . get ( 'command' , None ) timestamp = cherrypy . request . json . get ( 'timestamp' , None ) element = cherrypy . request . json . get ( 'element' , None ) host = cherrypy . request . json . get ( 'host' , None ) service = cherrypy . request . json . get ( 'service' , None ) user = cherrypy . request . json . get ( 'user' , None ) parameters = cherrypy . request . json . get ( 'parameters' , None ) except AttributeError : return { '_status' : u'ERR' , '_message' : u'Missing command parameters' } if not command : return { '_status' : u'ERR' , '_message' : u'Missing command parameter' } fields = split_semicolon ( command ) command_line = command . replace ( fields [ 0 ] , fields [ 0 ] . upper ( ) ) if timestamp : try : timestamp = int ( timestamp ) except ValueError : return { '_status' : u'ERR' , '_message' : u'Timestamp must be an integer value' } command_line = '[%d] %s' % ( timestamp , command_line ) if host or service or user : if host : command_line = '%s;%s' % ( command_line , host ) if service : command_line = '%s;%s' % ( command_line , service ) if user : command_line = '%s;%s' % ( command_line , user ) elif element : if '/' in element : # Replace only the first / element = element . replace ( '/' , ';' , 1 ) command_line = '%s;%s' % ( command_line , element ) if parameters : command_line = '%s;%s' % ( command_line , parameters ) # Add a command to get managed logger . warning ( "Got an external command: %s" , command_line ) self . app . add ( ExternalCommand ( command_line ) ) return { '_status' : u'OK' , '_message' : u"Got command: %s" % command_line , 'command' : command_line } | Request to execute an external command | 603 | 6 |
19,611 | def monitoring_problems ( self ) : res = self . identity ( ) res [ 'problems' ] = { } for scheduler_link in self . app . conf . schedulers : sched_res = scheduler_link . con . get ( 'monitoring_problems' , wait = True ) res [ 'problems' ] [ scheduler_link . name ] = { } if '_freshness' in sched_res : res [ 'problems' ] [ scheduler_link . name ] . update ( { '_freshness' : sched_res [ '_freshness' ] } ) if 'problems' in sched_res : res [ 'problems' ] [ scheduler_link . name ] . update ( { 'problems' : sched_res [ 'problems' ] } ) res [ '_freshness' ] = int ( time . time ( ) ) return res | Get Alignak detailed monitoring status | 197 | 7 |
19,612 | def livesynthesis ( self ) : res = self . identity ( ) res . update ( self . app . get_livesynthesis ( ) ) return res | Get Alignak live synthesis | 32 | 6 |
19,613 | def object ( self , o_type , o_name = None ) : for scheduler_link in self . app . conf . schedulers : sched_res = scheduler_link . con . get ( 'object' , { 'o_type' : o_type , 'o_name' : o_name } , wait = True ) if isinstance ( sched_res , dict ) and 'content' in sched_res : return sched_res return { '_status' : u'ERR' , '_message' : u'Required %s not found.' % o_type } | Get a monitored object from the arbiter . | 129 | 9 |
19,614 | def status ( self , details = False ) : if details is not False : details = bool ( details ) return self . app . get_alignak_status ( details = details ) | Get the overall alignak status | 38 | 6 |
19,615 | def events_log ( self , details = False , count = 0 , timestamp = 0 ) : if not count : count = 1 + int ( os . environ . get ( 'ALIGNAK_EVENTS_LOG_COUNT' , self . app . conf . events_log_count ) ) count = int ( count ) timestamp = float ( timestamp ) logger . debug ( 'Get max %d events, newer than %s out of %d' , count , timestamp , len ( self . app . recent_events ) ) res = [ ] for log in reversed ( self . app . recent_events ) : if timestamp and timestamp > log [ 'timestamp' ] : break if not count : break if details : # Exposes the full object res . append ( log ) else : res . append ( "%s - %s - %s" % ( log [ 'date' ] , log [ 'level' ] [ 0 ] . upper ( ) , log [ 'message' ] ) ) logger . debug ( 'Got %d events' , len ( res ) ) return res | Get the most recent Alignak events | 229 | 8 |
19,616 | def satellites_list ( self , daemon_type = '' ) : with self . app . conf_lock : res = { } for s_type in [ 'arbiter' , 'scheduler' , 'poller' , 'reactionner' , 'receiver' , 'broker' ] : if daemon_type and daemon_type != s_type : continue satellite_list = [ ] res [ s_type ] = satellite_list for daemon_link in getattr ( self . app . conf , s_type + 's' , [ ] ) : satellite_list . append ( daemon_link . name ) return res | Get the arbiter satellite names sorted by type | 137 | 9 |
19,617 | def satellites_configuration ( self ) : res = { } for s_type in [ 'arbiter' , 'scheduler' , 'poller' , 'reactionner' , 'receiver' , 'broker' ] : lst = [ ] res [ s_type ] = lst for daemon in getattr ( self . app . conf , s_type + 's' ) : cls = daemon . __class__ env = { } all_props = [ cls . properties , cls . running_properties ] for props in all_props : for prop in props : if not hasattr ( daemon , prop ) : continue if prop in [ "realms" , "conf" , "con" , "tags" , "modules" , "cfg" , "broks" , "cfg_to_manage" ] : continue val = getattr ( daemon , prop ) # give a try to a json able object try : json . dumps ( val ) env [ prop ] = val except TypeError as exp : logger . warning ( 'satellites_configuration, %s: %s' , prop , str ( exp ) ) lst . append ( env ) return res | Return all the configuration data of satellites | 260 | 7 |
19,618 | def external_commands ( self ) : res = [ ] with self . app . external_commands_lock : for cmd in self . app . get_external_commands ( ) : res . append ( cmd . serialize ( ) ) return res | Get the external commands from the daemon | 54 | 7 |
19,619 | def search ( self ) : # pylint: disable=no-self-use logger . debug ( "Grafana search... %s" , cherrypy . request . method ) if cherrypy . request . method == 'OPTIONS' : cherrypy . response . headers [ 'Access-Control-Allow-Methods' ] = 'GET,POST,PATCH,PUT,DELETE' cherrypy . response . headers [ 'Access-Control-Allow-Headers' ] = 'Content-Type,Authorization' cherrypy . response . headers [ 'Access-Control-Allow-Origin' ] = '*' cherrypy . request . handler = None return { } if getattr ( cherrypy . request , 'json' , None ) : logger . debug ( "Posted data: %s" , cherrypy . request . json ) logger . debug ( "Grafana search returns: %s" , GRAFANA_TARGETS ) return GRAFANA_TARGETS | Request available queries | 212 | 3 |
19,620 | def _build_host_livestate ( self , host_name , livestate ) : # pylint: disable=no-self-use, too-many-locals state = livestate . get ( 'state' , 'UP' ) . upper ( ) output = livestate . get ( 'output' , '' ) long_output = livestate . get ( 'long_output' , '' ) perf_data = livestate . get ( 'perf_data' , '' ) try : timestamp = int ( livestate . get ( 'timestamp' , 'ABC' ) ) except ValueError : timestamp = None host_state_to_id = { "UP" : 0 , "DOWN" : 1 , "UNREACHABLE" : 2 } parameters = '%s;%s' % ( host_state_to_id . get ( state , 3 ) , output ) if long_output and perf_data : parameters = '%s|%s\n%s' % ( parameters , perf_data , long_output ) elif long_output : parameters = '%s\n%s' % ( parameters , long_output ) elif perf_data : parameters = '%s|%s' % ( parameters , perf_data ) command_line = 'PROCESS_HOST_CHECK_RESULT;%s;%s' % ( host_name , parameters ) if timestamp is not None : command_line = '[%d] %s' % ( timestamp , command_line ) else : command_line = '[%d] %s' % ( int ( time . time ( ) ) , command_line ) return command_line | Build and notify the external command for an host livestate | 360 | 11 |
19,621 | def _build_service_livestate ( self , host_name , service_name , livestate ) : # pylint: disable=no-self-use, too-many-locals state = livestate . get ( 'state' , 'OK' ) . upper ( ) output = livestate . get ( 'output' , '' ) long_output = livestate . get ( 'long_output' , '' ) perf_data = livestate . get ( 'perf_data' , '' ) try : timestamp = int ( livestate . get ( 'timestamp' , 'ABC' ) ) except ValueError : timestamp = None service_state_to_id = { "OK" : 0 , "WARNING" : 1 , "CRITICAL" : 2 , "UNKNOWN" : 3 , "UNREACHABLE" : 4 } parameters = '%s;%s' % ( service_state_to_id . get ( state , 3 ) , output ) if long_output and perf_data : parameters = '%s|%s\n%s' % ( parameters , perf_data , long_output ) elif long_output : parameters = '%s\n%s' % ( parameters , long_output ) elif perf_data : parameters = '%s|%s' % ( parameters , perf_data ) command_line = 'PROCESS_SERVICE_CHECK_RESULT;%s;%s;%s' % ( host_name , service_name , parameters ) if timestamp is not None : command_line = '[%d] %s' % ( timestamp , command_line ) else : command_line = '[%d] %s' % ( int ( time . time ( ) ) , command_line ) return command_line | Build and notify the external command for a service livestate | 386 | 11 |
19,622 | def _do_not_run ( self ) : # If I'm the master, ignore the command and raise a log if self . app . is_master : message = "Received message to not run. " "I am the Master arbiter, ignore and continue to run." logger . warning ( message ) return { '_status' : u'ERR' , '_message' : message } # Else, I'm just a spare, so I listen to my master logger . debug ( "Received message to not run. I am the spare, stopping." ) self . app . last_master_speak = time . time ( ) self . app . must_run = False return { '_status' : u'OK' , '_message' : message } | The master arbiter tells to its spare arbiters to not run . | 163 | 14 |
19,623 | def create_commandcall ( prop , commands , command ) : cc = { 'commands' : commands , 'call' : command } if hasattr ( prop , 'enable_environment_macros' ) : cc [ 'enable_environment_macros' ] = prop . enable_environment_macros if hasattr ( prop , 'poller_tag' ) : cc [ 'poller_tag' ] = prop . poller_tag elif hasattr ( prop , 'reactionner_tag' ) : cc [ 'reactionner_tag' ] = prop . reactionner_tag return CommandCall ( cc ) | Create CommandCall object with command | 134 | 6 |
19,624 | def _push_broks ( self ) : data = cherrypy . request . json with self . app . arbiter_broks_lock : logger . debug ( "Pushing %d broks" , len ( data [ 'broks' ] ) ) self . app . arbiter_broks . extend ( [ unserialize ( elem , True ) for elem in data [ 'broks' ] ] ) | Push the provided broks objects to the broker daemon | 90 | 10 |
19,625 | def load_params ( self , params ) : logger . debug ( "Alignak parameters:" ) for key , value in sorted ( self . clean_params ( params ) . items ( ) ) : update_attribute = None # Maybe it's a variable as $USER$ or $ANOTHERVARIABLE$ # so look at the first character. If it's a $, it is a macro variable # if it ends with $ too if key [ 0 ] == '$' and key [ - 1 ] == '$' : key = key [ 1 : - 1 ] # Update the macros list if key not in self . __class__ . macros : logger . debug ( "New macro %s: %s - %s" , self , key , value ) self . __class__ . macros [ key ] = '$%s$' % key key = '$%s$' % key logger . debug ( "- macro %s" , key ) update_attribute = value # Create a new property to store the macro value if isinstance ( value , list ) : self . __class__ . properties [ key ] = ListProp ( default = value ) else : self . __class__ . properties [ key ] = StringProp ( default = value ) elif key in self . properties : update_attribute = self . properties [ key ] . pythonize ( value ) elif key in self . running_properties : logger . warning ( "using a the running property %s in a config file" , key ) update_attribute = self . running_properties [ key ] . pythonize ( value ) elif key . startswith ( '$' ) or key in [ 'cfg_file' , 'cfg_dir' ] : # it's a macro or a useless now param, we don't touch this update_attribute = value else : logger . debug ( "Guessing the property '%s' type because it " "is not in %s object properties" , key , self . __class__ . __name__ ) update_attribute = ToGuessProp ( ) . pythonize ( value ) if update_attribute is not None : setattr ( self , key , update_attribute ) logger . debug ( "- update %s = %s" , key , update_attribute ) # Change Nagios2 names to Nagios3 ones (before using them) self . old_properties_names_to_new ( ) # Fill default for myself - new properties entry becomes a self attribute self . fill_default ( ) | Load parameters from main configuration file | 530 | 6 |
19,626 | def _cut_line ( line ) : # punct = '"#$%&\'()*+/<=>?@[\\]^`{|}~' if re . search ( "([\t\n\r]+|[\x0b\x0c ]{3,})+" , line ) : tmp = re . split ( "([\t\n\r]+|[\x0b\x0c ]{3,})+" , line , 1 ) else : tmp = re . split ( "[" + string . whitespace + "]+" , line , 1 ) res = [ elt . strip ( ) for elt in tmp if elt . strip ( ) != '' ] return res | Split the line on whitespaces and remove empty chunks | 158 | 10 |
19,627 | def add_self_defined_objects ( raw_objects ) : logger . info ( "- creating internally defined commands..." ) if 'command' not in raw_objects : raw_objects [ 'command' ] = [ ] # Business rule raw_objects [ 'command' ] . append ( { 'command_name' : 'bp_rule' , 'command_line' : 'bp_rule' , 'imported_from' : 'alignak-self' } ) # Internal host checks raw_objects [ 'command' ] . append ( { 'command_name' : '_internal_host_up' , 'command_line' : '_internal_host_up' , 'imported_from' : 'alignak-self' } ) raw_objects [ 'command' ] . append ( { 'command_name' : '_internal_host_check' , # Command line must contain: state_id;output 'command_line' : '_internal_host_check;$ARG1$;$ARG2$' , 'imported_from' : 'alignak-self' } ) # Internal service check raw_objects [ 'command' ] . append ( { 'command_name' : '_echo' , 'command_line' : '_echo' , 'imported_from' : 'alignak-self' } ) raw_objects [ 'command' ] . append ( { 'command_name' : '_internal_service_check' , # Command line must contain: state_id;output 'command_line' : '_internal_service_check;$ARG1$;$ARG2$' , 'imported_from' : 'alignak-self' } ) | Add self defined command objects for internal processing ; bp_rule _internal_host_up _echo _internal_host_check _interna_service_check | 374 | 34 |
19,628 | def early_create_objects ( self , raw_objects ) : types_creations = self . __class__ . types_creations early_created_types = self . __class__ . early_created_types logger . info ( "Creating objects..." ) for o_type in sorted ( types_creations ) : if o_type in early_created_types : self . create_objects_for_type ( raw_objects , o_type ) logger . info ( "Done" ) | Create the objects needed for the post configuration file initialization | 105 | 10 |
19,629 | def create_objects ( self , raw_objects ) : types_creations = self . __class__ . types_creations early_created_types = self . __class__ . early_created_types logger . info ( "Creating objects..." ) # Before really creating the objects, we add some ghost # ones like the bp_rule for correlation self . add_self_defined_objects ( raw_objects ) for o_type in sorted ( types_creations ) : if o_type not in early_created_types : self . create_objects_for_type ( raw_objects , o_type ) logger . info ( "Done" ) | Create all the objects got after the post configuration file initialization | 139 | 11 |
19,630 | def create_objects_for_type ( self , raw_objects , o_type ) : # Ex: the above code do for timeperiods: # timeperiods = [] # for timeperiodcfg in objects['timeperiod']: # t = Timeperiod(timeperiodcfg) # timeperiods.append(t) # self.timeperiods = Timeperiods(timeperiods) types_creations = self . __class__ . types_creations ( cls , clss , prop , initial_index , _ ) = types_creations [ o_type ] # List to store the created objects lst = [ ] try : logger . info ( "- creating '%s' objects" , o_type ) for obj_cfg in raw_objects [ o_type ] : # We create the object my_object = cls ( obj_cfg ) # and append it to the list lst . append ( my_object ) if not lst : logger . info ( " none." ) except KeyError : logger . info ( " no %s objects in the configuration" , o_type ) # Create the objects list and set it in our properties setattr ( self , prop , clss ( lst , initial_index ) ) | Generic function to create objects regarding the o_type | 265 | 10 |
19,631 | def early_arbiter_linking ( self , arbiter_name , params ) : if not self . arbiters : params . update ( { 'name' : arbiter_name , 'arbiter_name' : arbiter_name , 'host_name' : socket . gethostname ( ) , 'address' : '127.0.0.1' , 'port' : 7770 , 'spare' : '0' } ) logger . warning ( "There is no arbiter, I add myself (%s) reachable on %s:%d" , arbiter_name , params [ 'address' ] , params [ 'port' ] ) arb = ArbiterLink ( params , parsing = True ) self . arbiters = ArbiterLinks ( [ arb ] ) # First fill default self . arbiters . fill_default ( ) self . modules . fill_default ( ) self . arbiters . linkify ( modules = self . modules ) self . modules . linkify ( ) | Prepare the arbiter for early operations | 217 | 8 |
19,632 | def linkify_one_command_with_commands ( self , commands , prop ) : if not hasattr ( self , prop ) : return command = getattr ( self , prop ) . strip ( ) if not command : setattr ( self , prop , None ) return data = { "commands" : commands , "call" : command } if hasattr ( self , 'poller_tag' ) : data . update ( { "poller_tag" : self . poller_tag } ) if hasattr ( self , 'reactionner_tag' ) : data . update ( { "reactionner_tag" : self . reactionner_tag } ) setattr ( self , prop , CommandCall ( data ) ) | Link a command | 157 | 3 |
19,633 | def linkify ( self ) : self . services . optimize_service_search ( self . hosts ) # First linkify myself like for some global commands self . linkify_one_command_with_commands ( self . commands , 'host_perfdata_command' ) self . linkify_one_command_with_commands ( self . commands , 'service_perfdata_command' ) self . linkify_one_command_with_commands ( self . commands , 'global_host_event_handler' ) self . linkify_one_command_with_commands ( self . commands , 'global_service_event_handler' ) # link hosts with timeperiods and commands self . hosts . linkify ( self . timeperiods , self . commands , self . contacts , self . realms , self . resultmodulations , self . businessimpactmodulations , self . escalations , self . hostgroups , self . checkmodulations , self . macromodulations ) self . hostsextinfo . merge ( self . hosts ) # Do the simplify AFTER explode groups # link hostgroups with hosts self . hostgroups . linkify ( self . hosts , self . realms , self . forced_realms_hostgroups ) # link services with other objects self . services . linkify ( self . hosts , self . commands , self . timeperiods , self . contacts , self . resultmodulations , self . businessimpactmodulations , self . escalations , self . servicegroups , self . checkmodulations , self . macromodulations ) self . servicesextinfo . merge ( self . services ) # link servicegroups members with services self . servicegroups . linkify ( self . hosts , self . services ) # link notificationways with timeperiods and commands self . notificationways . linkify ( self . timeperiods , self . commands ) # link notificationways with timeperiods and commands self . checkmodulations . linkify ( self . timeperiods , self . commands ) # Link with timeperiods self . macromodulations . linkify ( self . timeperiods ) # link contacgroups with contacts self . contactgroups . linkify ( self . contacts ) # link contacts with timeperiods and commands self . contacts . linkify ( self . commands , self . notificationways ) # link timeperiods with timeperiods (exclude part) self . timeperiods . linkify ( ) self . servicedependencies . linkify ( self . hosts , self . services , self . timeperiods ) self . hostdependencies . linkify ( self . hosts , self . timeperiods ) self . resultmodulations . linkify ( self . timeperiods ) self . businessimpactmodulations . linkify ( self . timeperiods ) self . escalations . linkify ( self . timeperiods , self . contacts , self . services , self . hosts ) # Link all satellite links with modules self . schedulers . linkify ( self . modules ) self . brokers . linkify ( self . modules ) self . receivers . linkify ( self . modules ) self . reactionners . linkify ( self . modules ) self . pollers . linkify ( self . modules ) # Ok, now update all realms with back links of satellites satellites = { } for sat in self . schedulers : satellites [ sat . uuid ] = sat for sat in self . pollers : satellites [ sat . uuid ] = sat for sat in self . reactionners : satellites [ sat . uuid ] = sat for sat in self . receivers : satellites [ sat . uuid ] = sat for sat in self . brokers : satellites [ sat . uuid ] = sat self . realms . prepare_satellites ( satellites ) | Make links between elements like a host got a services list with all its services in it | 792 | 17 |
19,634 | def clean ( self ) : logger . debug ( "Cleaning configuration objects before configuration sending:" ) types_creations = self . __class__ . types_creations for o_type in types_creations : ( _ , _ , inner_property , _ , _ ) = types_creations [ o_type ] logger . debug ( " . for %s" , inner_property , ) inner_object = getattr ( self , inner_property ) inner_object . clean ( ) | Wrapper for calling the clean method of services attribute | 104 | 10 |
19,635 | def warn_about_unmanaged_parameters ( self ) : properties = self . __class__ . properties unmanaged = [ ] for prop , entry in list ( properties . items ( ) ) : if not entry . managed and hasattr ( self , prop ) : if entry . help : line = "%s: %s" % ( prop , entry . help ) else : line = prop unmanaged . append ( line ) if unmanaged : logger . warning ( "The following Nagios legacy parameter(s) are not currently " "managed by Alignak:" ) for line in unmanaged : logger . warning ( '- %s' , line ) logger . warning ( "Those are unmanaged configuration statements, do you really need it? " "Create an issue on the Alignak repository or submit a pull " "request: http://www.github.com/Alignak-monitoring/alignak" ) | used to raise warning if the user got parameter that we do not manage from now | 193 | 16 |
19,636 | def apply_dependencies ( self ) : self . hosts . apply_dependencies ( ) self . services . apply_dependencies ( self . hosts ) | Creates dependencies links between elements . | 32 | 7 |
19,637 | def fill_default_configuration ( self ) : logger . debug ( "Filling the unset properties with their default value:" ) types_creations = self . __class__ . types_creations for o_type in types_creations : ( _ , _ , inner_property , _ , _ ) = types_creations [ o_type ] # Not yet for the realms and daemons links if inner_property in [ 'realms' , 'arbiters' , 'schedulers' , 'reactionners' , 'pollers' , 'brokers' , 'receivers' ] : continue logger . debug ( " . for %s" , inner_property , ) inner_object = getattr ( self , inner_property , None ) if inner_object is None : logger . debug ( "No %s to fill with default values" , inner_property ) continue inner_object . fill_default ( ) # We have all monitored elements, we can create a default realm if none is defined if getattr ( self , 'realms' , None ) is not None : self . fill_default_realm ( ) self . realms . fill_default ( ) # Then we create missing satellites, so no other satellites will be created after self . fill_default_satellites ( self . launch_missing_daemons ) types_creations = self . __class__ . types_creations for o_type in types_creations : ( _ , _ , inner_property , _ , _ ) = types_creations [ o_type ] if getattr ( self , inner_property , None ) is None : logger . debug ( "No %s to fill with default values" , inner_property ) continue # Only for the daemons links if inner_property in [ 'schedulers' , 'reactionners' , 'pollers' , 'brokers' , 'receivers' ] : logger . debug ( " . for %s" , inner_property , ) inner_object = getattr ( self , inner_property ) inner_object . fill_default ( ) # Now fill some fields we can predict (like address for hosts) self . hosts . fill_predictive_missing_parameters ( ) self . services . fill_predictive_missing_parameters ( ) | Fill objects properties with default value if necessary | 501 | 8 |
19,638 | def log_daemons_list ( self ) : daemons = [ self . arbiters , self . schedulers , self . pollers , self . brokers , self . reactionners , self . receivers ] for daemons_list in daemons : if not daemons_list : logger . debug ( "- %ss: None" , daemons_list . inner_class . my_type ) else : logger . debug ( "- %ss: %s" , daemons_list . inner_class . my_type , ',' . join ( [ daemon . get_name ( ) for daemon in daemons_list ] ) ) | Log Alignak daemons list | 142 | 8 |
19,639 | def got_broker_module_type_defined ( self , module_type ) : for broker_link in self . brokers : for module in broker_link . modules : if module . is_a_module ( module_type ) : return True return False | Check if a module type is defined in one of the brokers | 55 | 12 |
19,640 | def got_scheduler_module_type_defined ( self , module_type ) : for scheduler_link in self . schedulers : for module in scheduler_link . modules : if module . is_a_module ( module_type ) : return True return False | Check if a module type is defined in one of the schedulers | 60 | 14 |
19,641 | def got_arbiter_module_type_defined ( self , module_type ) : for arbiter in self . arbiters : # Do like the linkify will do after.... for module in getattr ( arbiter , 'modules' , [ ] ) : # So look at what the arbiter try to call as module module_name = module . get_name ( ) # Ok, now look in modules... for mod in self . modules : # try to see if this module is the good type if getattr ( mod , 'python_name' , '' ) . strip ( ) == module_type . strip ( ) : # if so, the good name? if getattr ( mod , 'name' , '' ) . strip ( ) == module_name : return True return False | Check if a module type is defined in one of the arbiters Also check the module name | 166 | 18 |
19,642 | def create_business_rules ( self ) : self . hosts . create_business_rules ( self . hosts , self . services , self . hostgroups , self . servicegroups , self . macromodulations , self . timeperiods ) self . services . create_business_rules ( self . hosts , self . services , self . hostgroups , self . servicegroups , self . macromodulations , self . timeperiods ) | Create business rules for hosts and services | 92 | 7 |
19,643 | def create_business_rules_dependencies ( self ) : for item in itertools . chain ( self . hosts , self . services ) : if not item . got_business_rule : continue bp_items = item . business_rule . list_all_elements ( ) for bp_item_uuid in bp_items : if bp_item_uuid in self . hosts : bp_item = self . hosts [ bp_item_uuid ] notif_options = item . business_rule_host_notification_options else : # We have a service bp_item = self . services [ bp_item_uuid ] notif_options = item . business_rule_service_notification_options if notif_options : bp_item . notification_options = notif_options bp_item . act_depend_of_me . append ( ( item . uuid , [ 'd' , 'u' , 's' , 'f' , 'c' , 'w' , 'x' ] , '' , True ) ) # TODO: Is it necessary? We already have this info in act_depend_* attributes item . parent_dependencies . add ( bp_item . uuid ) bp_item . child_dependencies . add ( item . uuid ) | Create business rules dependencies for hosts and services | 292 | 8 |
19,644 | def propagate_timezone_option ( self ) : if self . use_timezone : # first apply myself os . environ [ 'TZ' ] = self . use_timezone time . tzset ( ) tab = [ self . schedulers , self . pollers , self . brokers , self . receivers , self . reactionners ] for sat_list in tab : for sat in sat_list : if sat . use_timezone == 'NOTSET' : setattr ( sat , 'use_timezone' , self . use_timezone ) | Set our timezone value and give it too to unset satellites | 120 | 13 |
19,645 | def linkify_templates ( self ) : self . hosts . linkify_templates ( ) self . contacts . linkify_templates ( ) self . services . linkify_templates ( ) self . servicedependencies . linkify_templates ( ) self . hostdependencies . linkify_templates ( ) self . timeperiods . linkify_templates ( ) self . hostsextinfo . linkify_templates ( ) self . servicesextinfo . linkify_templates ( ) self . escalations . linkify_templates ( ) # But also old srv and host escalations self . serviceescalations . linkify_templates ( ) self . hostescalations . linkify_templates ( ) | Like for normal object we link templates with each others | 158 | 10 |
19,646 | def remove_templates ( self ) : self . hosts . remove_templates ( ) self . contacts . remove_templates ( ) self . services . remove_templates ( ) self . servicedependencies . remove_templates ( ) self . hostdependencies . remove_templates ( ) self . timeperiods . remove_templates ( ) | Clean useless elements like templates because they are not needed anymore | 76 | 11 |
19,647 | def show_errors ( self ) : if self . configuration_warnings : logger . warning ( "Configuration warnings:" ) for msg in self . configuration_warnings : logger . warning ( msg ) if self . configuration_errors : logger . warning ( "Configuration errors:" ) for msg in self . configuration_errors : logger . warning ( msg ) | Loop over configuration warnings and log them as INFO log Loop over configuration errors and log them as INFO log | 72 | 20 |
19,648 | def prepare_for_sending ( self ) : if [ arbiter_link for arbiter_link in self . arbiters if arbiter_link . spare ] : logger . info ( 'Serializing the configuration for my spare arbiter...' ) # Now serialize the whole configuration, for sending to spare arbiters self . spare_arbiter_conf = serialize ( self ) | The configuration needs to be serialized before being sent to a spare arbiter | 82 | 15 |
19,649 | def dump ( self , dump_file_name = None ) : config_dump = { } for _ , _ , category , _ , _ in list ( self . types_creations . values ( ) ) : try : objs = [ jsonify_r ( i ) for i in getattr ( self , category ) ] except ( TypeError , AttributeError ) : # pragma: no cover, simple protection logger . warning ( "Dumping configuration, '%s' not present in the configuration" , category ) continue container = getattr ( self , category ) if category == "services" : objs = sorted ( objs , key = lambda o : "%s/%s" % ( o [ "host_name" ] , o [ "service_description" ] ) ) elif hasattr ( container , "name_property" ) : name_prop = container . name_property objs = sorted ( objs , key = lambda o , prop = name_prop : getattr ( o , prop , '' ) ) config_dump [ category ] = objs if not dump_file_name : dump_file_name = os . path . join ( tempfile . gettempdir ( ) , 'alignak-%s-cfg-dump-%d.json' % ( self . name , int ( time . time ( ) ) ) ) try : logger . info ( 'Dumping configuration to: %s' , dump_file_name ) fd = open ( dump_file_name , "w" ) fd . write ( json . dumps ( config_dump , indent = 4 , separators = ( ',' , ': ' ) , sort_keys = True ) ) fd . close ( ) logger . info ( 'Dumped' ) except ( OSError , IndexError ) as exp : # pragma: no cover, should never happen... logger . critical ( "Error when dumping configuration to %s: %s" , dump_file_name , str ( exp ) ) | Dump configuration to a file in a JSON format | 429 | 10 |
19,650 | def push_broks_to_broker ( self ) : # pragma: no cover - not used! someone_is_concerned = False sent = False for broker_link in self . conf . brokers : # Send only if the broker is concerned... if not broker_link . manage_arbiters : continue someone_is_concerned = True if broker_link . reachable : logger . debug ( "Sending %d broks to the broker %s" , len ( self . broks ) , broker_link . name ) if broker_link . push_broks ( self . broks ) : statsmgr . counter ( 'broks.pushed.count' , len ( self . broks ) ) sent = True if not someone_is_concerned or sent : # No one is anymore interested with... del self . broks [ : ] | Send all broks from arbiter internal list to broker | 186 | 11 |
19,651 | def push_external_commands_to_schedulers ( self ) : # pragma: no cover - not used! # Now get all external commands and push them to the schedulers for external_command in self . external_commands : self . external_commands_manager . resolve_command ( external_command ) # Now for all reachable schedulers, send the commands sent = False for scheduler_link in self . conf . schedulers : ext_cmds = scheduler_link . external_commands if ext_cmds and scheduler_link . reachable : logger . debug ( "Sending %d commands to the scheduler %s" , len ( ext_cmds ) , scheduler_link . name ) if scheduler_link . push_external_commands ( ext_cmds ) : statsmgr . counter ( 'external-commands.pushed.count' , len ( ext_cmds ) ) sent = True if sent : # Clean the pushed commands scheduler_link . external_commands . clear ( ) | Send external commands to schedulers | 231 | 7 |
19,652 | def get_broks_from_satellites ( self ) : # pragma: no cover - not used! for satellites in [ self . conf . brokers , self . conf . schedulers , self . conf . pollers , self . conf . reactionners , self . conf . receivers ] : for satellite in satellites : # Get only if reachable... if not satellite . reachable : continue logger . debug ( "Getting broks from: %s" , satellite . name ) new_broks = satellite . get_and_clear_broks ( ) if new_broks : logger . debug ( "Got %d broks from: %s" , len ( new_broks ) , satellite . name ) for brok in new_broks : self . add ( brok ) | Get broks from my all internal satellite links | 169 | 9 |
19,653 | def get_initial_broks_from_satellites ( self ) : for satellites in [ self . conf . brokers , self . conf . schedulers , self . conf . pollers , self . conf . reactionners , self . conf . receivers ] : for satellite in satellites : # Get only if reachable... if not satellite . reachable : continue logger . debug ( "Getting initial brok from: %s" , satellite . name ) brok = satellite . get_initial_status_brok ( ) logger . debug ( "Satellite '%s' initial brok: %s" , satellite . name , brok ) self . add ( brok ) | Get initial broks from my internal satellite links | 143 | 9 |
19,654 | def load_modules_configuration_objects ( self , raw_objects ) : # pragma: no cover, # not yet with unit tests. # Now we ask for configuration modules if they # got items for us for instance in self . modules_manager . instances : logger . debug ( "Getting objects from the module: %s" , instance . name ) if not hasattr ( instance , 'get_objects' ) : logger . debug ( "The module '%s' do not provide any objects." , instance . name ) return try : logger . info ( "Getting Alignak monitored configuration objects from module '%s'" , instance . name ) got_objects = instance . get_objects ( ) except Exception as exp : # pylint: disable=broad-except logger . exception ( "Module %s get_objects raised an exception %s. " "Log and continue to run." , instance . name , exp ) continue if not got_objects : logger . warning ( "The module '%s' did not provided any objects." , instance . name ) return types_creations = self . conf . types_creations for o_type in types_creations : ( _ , _ , prop , _ , _ ) = types_creations [ o_type ] if prop in [ 'arbiters' , 'brokers' , 'schedulers' , 'pollers' , 'reactionners' , 'receivers' , 'modules' ] : continue if prop not in got_objects : logger . warning ( "Did not get any '%s' objects from %s" , prop , instance . name ) continue for obj in got_objects [ prop ] : # test if raw_objects[k] are already set - if not, add empty array if o_type not in raw_objects : raw_objects [ o_type ] = [ ] # Update the imported_from property if the module did not set if 'imported_from' not in obj : obj [ 'imported_from' ] = 'module:%s' % instance . name # Append to the raw objects raw_objects [ o_type ] . append ( obj ) logger . debug ( "Added %i %s objects from %s" , len ( got_objects [ prop ] ) , o_type , instance . name ) | Load configuration objects from arbiter modules If module implements get_objects arbiter will call it and add create objects | 496 | 22 |
19,655 | def load_modules_alignak_configuration ( self ) : # pragma: no cover, not yet with unit tests. alignak_cfg = { } # Ask configured modules if they got configuration for us for instance in self . modules_manager . instances : if not hasattr ( instance , 'get_alignak_configuration' ) : return try : logger . info ( "Getting Alignak global configuration from module '%s'" , instance . name ) cfg = instance . get_alignak_configuration ( ) alignak_cfg . update ( cfg ) except Exception as exp : # pylint: disable=broad-except logger . error ( "Module %s get_alignak_configuration raised an exception %s. " "Log and continue to run" , instance . name , str ( exp ) ) output = io . StringIO ( ) traceback . print_exc ( file = output ) logger . error ( "Back trace of this remove: %s" , output . getvalue ( ) ) output . close ( ) continue params = [ ] if alignak_cfg : logger . info ( "Got Alignak global configuration:" ) for key , value in sorted ( alignak_cfg . items ( ) ) : logger . info ( "- %s = %s" , key , value ) # properties starting with an _ character are "transformed" to macro variables if key . startswith ( '_' ) : key = '$' + key [ 1 : ] . upper ( ) + '$' # properties valued as None are filtered if value is None : continue # properties valued as None string are filtered if value == 'None' : continue # properties valued as empty strings are filtered if value == '' : continue # set properties as legacy Shinken configuration files params . append ( "%s=%s" % ( key , value ) ) self . conf . load_params ( params ) | Load Alignak configuration from the arbiter modules If module implements get_alignak_configuration call this function | 405 | 23 |
19,656 | def request_stop ( self , message = '' , exit_code = 0 ) : # Only a master arbiter can stop the daemons if self . is_master : # Stop the daemons self . daemons_stop ( timeout = self . conf . daemons_stop_timeout ) # Request the daemon stop super ( Arbiter , self ) . request_stop ( message , exit_code ) | Stop the Arbiter daemon | 88 | 5 |
19,657 | def start_daemon ( self , satellite ) : logger . info ( " launching a daemon for: %s/%s..." , satellite . type , satellite . name ) # The daemon startup script location may be defined in the configuration daemon_script_location = getattr ( self . conf , 'daemons_script_location' , self . bindir ) if not daemon_script_location : daemon_script_location = "alignak-%s" % satellite . type else : daemon_script_location = "%s/alignak-%s" % ( daemon_script_location , satellite . type ) # Some extra arguments may be defined in the Alignak configuration daemon_arguments = getattr ( self . conf , 'daemons_arguments' , '' ) args = [ daemon_script_location , "--name" , satellite . name , "--environment" , self . env_filename , "--host" , str ( satellite . host ) , "--port" , str ( satellite . port ) ] if daemon_arguments : args . append ( daemon_arguments ) logger . info ( " ... with some arguments: %s" , args ) try : process = psutil . Popen ( args , stdin = None , stdout = None , stderr = None ) # A brief pause... time . sleep ( 0.1 ) except Exception as exp : # pylint: disable=broad-except logger . error ( "Error when launching %s: %s" , satellite . name , exp ) logger . error ( "Command: %s" , args ) return False logger . info ( " %s launched (pid=%d, gids=%s)" , satellite . name , process . pid , process . gids ( ) ) # My satellites/daemons map self . my_daemons [ satellite . name ] = { 'satellite' : satellite , 'process' : process } return True | Manage the list of detected missing daemons | 415 | 10 |
19,658 | def daemons_start ( self , run_daemons = True ) : result = True if run_daemons : logger . info ( "Alignak configured daemons start:" ) else : logger . info ( "Alignak configured daemons check:" ) # Parse the list of the missing daemons and try to run the corresponding processes for satellites_list in [ self . conf . arbiters , self . conf . receivers , self . conf . reactionners , self . conf . pollers , self . conf . brokers , self . conf . schedulers ] : for satellite in satellites_list : logger . info ( "- found %s, to be launched: %s, address: %s" , satellite . name , satellite . alignak_launched , satellite . uri ) if satellite == self . link_to_myself : # Ignore myself ;) continue if satellite . alignak_launched and satellite . address not in [ '127.0.0.1' , 'localhost' ] : logger . error ( "Alignak is required to launch a daemon for %s %s " "but the satelitte is defined on an external address: %s" , satellite . type , satellite . name , satellite . address ) result = False continue if not run_daemons : # When checking, ignore the daemon launch part... continue if not satellite . alignak_launched : logger . debug ( "Alignak will not launch '%s'" ) continue if not satellite . active : logger . warning ( "- daemon '%s' is declared but not set as active, " "do not start..." , satellite . name ) continue if satellite . name in self . my_daemons : logger . warning ( "- daemon '%s' is already running" , satellite . name ) continue started = self . start_daemon ( satellite ) result = result and started return result | Manage the list of the daemons in the configuration | 405 | 12 |
19,659 | def daemons_stop ( self , timeout = 30 , kill_children = False ) : def on_terminate ( proc ) : """Process termination callback function""" logger . debug ( "process %s terminated with exit code %s" , proc . pid , proc . returncode ) result = True if self . my_daemons : logger . info ( "Alignak self-launched daemons stop:" ) start = time . time ( ) for daemon in list ( self . my_daemons . values ( ) ) : # Terminate the daemon and its children process procs = [ ] if kill_children : procs = daemon [ 'process' ] . children ( ) procs . append ( daemon [ 'process' ] ) for process in procs : try : logger . info ( "- terminating process %s" , process . name ( ) ) process . terminate ( ) except psutil . AccessDenied : logger . warning ( "Process %s is %s" , process . name ( ) , process . status ( ) ) procs = [ ] for daemon in list ( self . my_daemons . values ( ) ) : # Stop the daemon and its children process if kill_children : procs = daemon [ 'process' ] . children ( ) procs . append ( daemon [ 'process' ] ) _ , alive = psutil . wait_procs ( procs , timeout = timeout , callback = on_terminate ) if alive : # Kill processes for process in alive : logger . warning ( "Process %s did not stopped, trying to kill" , process . name ( ) ) process . kill ( ) _ , alive = psutil . wait_procs ( alive , timeout = timeout , callback = on_terminate ) if alive : # give up for process in alive : logger . warning ( "process %s survived SIGKILL; giving up" , process . name ( ) ) result = False logger . debug ( "Stopping daemons duration: %.2f seconds" , time . time ( ) - start ) return result | Stop the Alignak daemons | 439 | 8 |
19,660 | def wait_for_master_death ( self ) : logger . info ( "Waiting for master death" ) timeout = 1.0 self . last_master_ping = time . time ( ) master_timeout = 300 for arbiter_link in self . conf . arbiters : if not arbiter_link . spare : master_timeout = arbiter_link . spare_check_interval * arbiter_link . spare_max_check_attempts logger . info ( "I'll wait master death for %d seconds" , master_timeout ) while not self . interrupted : # Make a pause and check if the system time changed _ , tcdiff = self . make_a_pause ( timeout ) # If there was a system time change then we have to adapt last_master_ping: if tcdiff : self . last_master_ping += tcdiff if self . new_conf : self . setup_new_conf ( ) sys . stdout . write ( "." ) sys . stdout . flush ( ) # Now check if master is dead or not now = time . time ( ) if now - self . last_master_ping > master_timeout : logger . info ( "Arbiter Master is dead. The arbiter %s takes the lead!" , self . link_to_myself . name ) for arbiter_link in self . conf . arbiters : if not arbiter_link . spare : arbiter_link . alive = False self . must_run = True break | Wait for a master timeout and take the lead if necessary | 323 | 11 |
19,661 | def manage_signal ( self , sig , frame ) : # Request the arbiter to stop if sig in [ signal . SIGINT , signal . SIGTERM ] : logger . info ( "received a signal: %s" , SIGNALS_TO_NAMES_DICT [ sig ] ) self . kill_request = True self . kill_timestamp = time . time ( ) logger . info ( "request to stop in progress" ) else : Daemon . manage_signal ( self , sig , frame ) | Manage signals caught by the process Specific behavior for the arbiter when it receives a sigkill or sigterm | 110 | 22 |
19,662 | def do_before_loop ( self ) : logger . info ( "I am the arbiter: %s" , self . link_to_myself . name ) # If I am a spare, I do not have anything to do here... if not self . is_master : logger . debug ( "Waiting for my master death..." ) return # Arbiter check if some daemons need to be started if not self . daemons_start ( run_daemons = True ) : self . request_stop ( message = "Some Alignak daemons did not started correctly." , exit_code = 4 ) if not self . daemons_check ( ) : self . request_stop ( message = "Some Alignak daemons cannot be checked." , exit_code = 4 ) # Make a pause to let our started daemons get ready... pause = max ( 1 , max ( self . conf . daemons_start_timeout , len ( self . my_daemons ) * 0.5 ) ) if pause : logger . info ( "Pausing %.2f seconds..." , pause ) time . sleep ( pause ) # Prepare and dispatch the monitored configuration self . configuration_dispatch ( ) # Now we can get all initial broks for our satellites _t0 = time . time ( ) self . get_initial_broks_from_satellites ( ) statsmgr . timer ( 'broks.get-initial' , time . time ( ) - _t0 ) # Now create the external commands manager # We are a dispatcher: our role is to dispatch commands to the schedulers self . external_commands_manager = ExternalCommandManager ( self . conf , 'dispatcher' , self , self . conf . accept_passive_unknown_check_results , self . conf . log_external_commands ) | Called before the main daemon loop . | 400 | 8 |
19,663 | def get_monitoring_problems ( self ) : res = self . get_id ( ) res [ 'problems' ] = { } # Report our schedulers information, but only if a dispatcher exists if getattr ( self , 'dispatcher' , None ) is None : return res for satellite in self . dispatcher . all_daemons_links : if satellite . type not in [ 'scheduler' ] : continue if not satellite . active : continue if satellite . statistics and 'problems' in satellite . statistics : res [ 'problems' ] [ satellite . name ] = { '_freshness' : satellite . statistics [ '_freshness' ] , 'problems' : satellite . statistics [ 'problems' ] } return res | Get the schedulers satellites problems list | 163 | 8 |
19,664 | def get_livesynthesis ( self ) : res = self . get_id ( ) res [ 'livesynthesis' ] = { '_overall' : { '_freshness' : int ( time . time ( ) ) , 'livesynthesis' : { 'hosts_total' : 0 , 'hosts_not_monitored' : 0 , 'hosts_up_hard' : 0 , 'hosts_up_soft' : 0 , 'hosts_down_hard' : 0 , 'hosts_down_soft' : 0 , 'hosts_unreachable_hard' : 0 , 'hosts_unreachable_soft' : 0 , 'hosts_problems' : 0 , 'hosts_acknowledged' : 0 , 'hosts_in_downtime' : 0 , 'hosts_flapping' : 0 , 'services_total' : 0 , 'services_not_monitored' : 0 , 'services_ok_hard' : 0 , 'services_ok_soft' : 0 , 'services_warning_hard' : 0 , 'services_warning_soft' : 0 , 'services_critical_hard' : 0 , 'services_critical_soft' : 0 , 'services_unknown_hard' : 0 , 'services_unknown_soft' : 0 , 'services_unreachable_hard' : 0 , 'services_unreachable_soft' : 0 , 'services_problems' : 0 , 'services_acknowledged' : 0 , 'services_in_downtime' : 0 , 'services_flapping' : 0 , } } } # Report our schedulers information, but only if a dispatcher exists if getattr ( self , 'dispatcher' , None ) is None : return res for satellite in self . dispatcher . all_daemons_links : if satellite . type not in [ 'scheduler' ] : continue if not satellite . active : continue if 'livesynthesis' in satellite . statistics : # Scheduler detailed live synthesis res [ 'livesynthesis' ] [ satellite . name ] = { '_freshness' : satellite . statistics [ '_freshness' ] , 'livesynthesis' : satellite . statistics [ 'livesynthesis' ] } # Cumulated live synthesis for prop in res [ 'livesynthesis' ] [ '_overall' ] [ 'livesynthesis' ] : if prop in satellite . statistics [ 'livesynthesis' ] : res [ 'livesynthesis' ] [ '_overall' ] [ 'livesynthesis' ] [ prop ] += satellite . statistics [ 'livesynthesis' ] [ prop ] return res | Get the schedulers satellites live synthesis | 581 | 8 |
19,665 | def overall_state_id ( self ) : overall_state = 0 if not self . monitored : overall_state = 5 elif self . acknowledged : overall_state = 1 elif self . downtimed : overall_state = 2 elif self . state_type == 'HARD' : if self . state == 'WARNING' : overall_state = 3 elif self . state == 'CRITICAL' : overall_state = 4 elif self . state == 'UNKNOWN' : overall_state = 3 elif self . state == 'UNREACHABLE' : overall_state = 4 return overall_state | Get the service overall state . | 132 | 6 |
19,666 | def fill_predictive_missing_parameters ( self ) : if self . initial_state == 'w' : self . state = u'WARNING' elif self . initial_state == 'u' : self . state = u'UNKNOWN' elif self . initial_state == 'c' : self . state = u'CRITICAL' elif self . initial_state == 'x' : self . state = u'UNREACHABLE' | define state with initial_state | 100 | 6 |
19,667 | def get_name ( self ) : if hasattr ( self , 'service_description' ) : return self . service_description if hasattr ( self , 'name' ) : return self . name return 'SERVICE-DESCRIPTION-MISSING' | Accessor to service_description attribute or name if first not defined | 54 | 13 |
19,668 | def get_groupnames ( self , sgs ) : return ',' . join ( [ sgs [ sg ] . get_name ( ) for sg in self . servicegroups ] ) | Get servicegroups list | 41 | 4 |
19,669 | def duplicate ( self , host ) : # pylint: disable=too-many-locals duplicates = [ ] # In macro, it's all in UPPER case prop = self . duplicate_foreach . strip ( ) . upper ( ) if prop not in host . customs : # If I do not have the property, we bail out return duplicates # Get the list entry, and the not one if there is one entry = host . customs [ prop ] # Look at the list of the key we do NOT want maybe, # for _disks it will be _!disks not_entry = host . customs . get ( '_' + '!' + prop [ 1 : ] , '' ) . split ( ',' ) not_keys = strip_and_uniq ( not_entry ) default_value = getattr ( self , 'default_value' , '' ) # Transform the generator string to a list # Missing values are filled with the default value try : key_values = tuple ( generate_key_value_sequences ( entry , default_value ) ) except KeyValueSyntaxError as exc : fmt_dict = { 'prop' : self . duplicate_foreach , 'host' : host . get_name ( ) , 'svc' : self . service_description , 'entry' : entry , 'exc' : exc , } err = ( "The custom property %(prop)r of the " "host %(host)r is not a valid entry for a service generator: %(exc)s, " "with entry=%(entry)r" ) % fmt_dict logger . warning ( err ) host . add_error ( err ) return duplicates for key_value in key_values : key = key_value [ 'KEY' ] # Maybe this key is in the NOT list, if so, skip it if key in not_keys : continue new_s = self . copy ( ) new_s . host_name = host . get_name ( ) if self . is_tpl ( ) : # if template, the new one is not new_s . register = 1 for key in key_value : if key == 'KEY' : if hasattr ( self , 'service_description' ) : # We want to change all illegal chars to a _ sign. # We can't use class.illegal_obj_char # because in the "explode" phase, we do not have access to this data! :( safe_key_value = re . sub ( r'[' + "`~!$%^&*\"|'<>?,()=" + ']+' , '_' , key_value [ key ] ) new_s . service_description = self . service_description . replace ( '$' + key + '$' , safe_key_value ) # Here is a list of property where we will expand the $KEY$ by the value _the_expandables = [ 'check_command' , 'aggregation' , 'event_handler' ] for prop in _the_expandables : if hasattr ( self , prop ) : # here we can replace VALUE, VALUE1, VALUE2,... setattr ( new_s , prop , getattr ( new_s , prop ) . replace ( '$' + key + '$' , key_value [ key ] ) ) if hasattr ( self , 'service_dependencies' ) : for i , servicedep in enumerate ( new_s . service_dependencies ) : new_s . service_dependencies [ i ] = servicedep . replace ( '$' + key + '$' , key_value [ key ] ) # And then add in our list this new service duplicates . append ( new_s ) return duplicates | For a given host look for all copy we must create for for_each property | 812 | 16 |
19,670 | def set_state_from_exit_status ( self , status , notif_period , hosts , services ) : now = time . time ( ) # we should put in last_state the good last state: # if not just change the state by an problem/impact # we can take current state. But if it's the case, the # real old state is self.state_before_impact (it's the TRUE # state in fact) # but only if the global conf have enable the impact state change cls = self . __class__ if cls . enable_problem_impacts_states_change and self . is_impact and not self . state_changed_since_impact : self . last_state = self . state_before_impact else : # standard case self . last_state = self . state # The last times are kept as integer values rather than float... no need for ms! if status == 0 : self . state = u'OK' self . state_id = 0 self . last_time_ok = int ( self . last_state_update ) # self.last_time_ok = self.last_state_update state_code = 'o' elif status == 1 : self . state = u'WARNING' self . state_id = 1 self . last_time_warning = int ( self . last_state_update ) # self.last_time_warning = self.last_state_update state_code = 'w' elif status == 2 : self . state = u'CRITICAL' self . state_id = 2 self . last_time_critical = int ( self . last_state_update ) # self.last_time_critical = self.last_state_update state_code = 'c' elif status == 3 : self . state = u'UNKNOWN' self . state_id = 3 self . last_time_unknown = int ( self . last_state_update ) # self.last_time_unknown = self.last_state_update state_code = 'u' elif status == 4 : self . state = u'UNREACHABLE' self . state_id = 4 self . last_time_unreachable = int ( self . last_state_update ) # self.last_time_unreachable = self.last_state_update state_code = 'x' else : self . state = u'CRITICAL' # exit code UNDETERMINED self . state_id = 2 self . last_time_critical = int ( self . last_state_update ) # self.last_time_critical = self.last_state_update state_code = 'c' if state_code in self . flap_detection_options : self . add_flapping_change ( self . state != self . last_state ) # Now we add a value, we update the is_flapping prop self . update_flapping ( notif_period , hosts , services ) if self . state != self . last_state : self . last_state_change = self . last_state_update self . duration_sec = now - self . last_state_change | Set the state in UP WARNING CRITICAL UNKNOWN or UNREACHABLE according to the status of a check result . | 685 | 25 |
19,671 | def is_state ( self , status ) : # pylint: disable=too-many-return-statements if status == self . state : return True # Now low status if status == 'o' and self . state == u'OK' : return True if status == 'c' and self . state == u'CRITICAL' : return True if status == 'w' and self . state == u'WARNING' : return True if status == 'u' and self . state == u'UNKNOWN' : return True if status == 'x' and self . state == u'UNREACHABLE' : return True return False | Return True if status match the current service status | 136 | 9 |
19,672 | def last_time_non_ok_or_up ( self ) : non_ok_times = [ x for x in [ self . last_time_warning , self . last_time_critical , self . last_time_unknown ] if x > self . last_time_ok ] if not non_ok_times : last_time_non_ok = 0 # todo: program_start would be better? else : last_time_non_ok = min ( non_ok_times ) return last_time_non_ok | Get the last time the service was in a non - OK state | 117 | 13 |
19,673 | def get_data_for_notifications ( self , contact , notif , host_ref ) : if not host_ref : return [ self , contact , notif ] return [ host_ref , self , contact , notif ] | Get data for a notification | 50 | 5 |
19,674 | def get_short_status ( self , hosts , services ) : mapping = { 0 : "O" , 1 : "W" , 2 : "C" , 3 : "U" , 4 : "N" , } if self . got_business_rule : return mapping . get ( self . business_rule . get_state ( hosts , services ) , "n/a" ) return mapping . get ( self . state_id , "n/a" ) | Get the short status of this host | 100 | 7 |
19,675 | def add_template ( self , tpl ) : objcls = self . inner_class . my_type name = getattr ( tpl , 'name' , '' ) sdesc = getattr ( tpl , 'service_description' , '' ) hname = getattr ( tpl , 'host_name' , '' ) logger . debug ( "Adding a %s template: host_name: %s, name: %s, service_description: %s" , objcls , hname , name , sdesc ) if not name and not hname : msg = "a %s template has been defined without name nor host_name. from: %s" % ( objcls , tpl . imported_from ) tpl . add_error ( msg ) elif not name and not sdesc : msg = "a %s template has been defined without name nor service_description. from: %s" % ( objcls , tpl . imported_from ) tpl . add_error ( msg ) elif not name : # If name is not defined, use the host_name_service_description as name (fix #791) setattr ( tpl , 'name' , "%s_%s" % ( hname , sdesc ) ) tpl = self . index_template ( tpl ) elif name : tpl = self . index_template ( tpl ) self . templates [ tpl . uuid ] = tpl logger . debug ( '\tAdded service template #%d %s' , len ( self . templates ) , tpl ) | Adds and index a template into the templates container . | 342 | 10 |
19,676 | def find_srvs_by_hostname ( self , host_name ) : if hasattr ( self , 'hosts' ) : host = self . hosts . find_by_name ( host_name ) if host is None : return None return host . get_services ( ) return None | Get all services from a host based on a host_name | 63 | 12 |
19,677 | def find_srv_by_name_and_hostname ( self , host_name , sdescr ) : key = ( host_name , sdescr ) return self . name_to_item . get ( key , None ) | Get a specific service based on a host_name and service_description | 52 | 14 |
19,678 | def linkify_s_by_hst ( self , hosts ) : for serv in self : # If we do not have a host_name, we set it as # a template element to delete. (like Nagios) if not hasattr ( serv , 'host_name' ) : serv . host = None continue try : hst_name = serv . host_name # The new member list, in id hst = hosts . find_by_name ( hst_name ) # Let the host know we are his service if hst is not None : serv . host = hst . uuid hst . add_service_link ( serv . uuid ) else : # Ok, the host do not exists! err = "Warning: the service '%s' got an invalid host_name '%s'" % ( serv . get_name ( ) , hst_name ) serv . configuration_warnings . append ( err ) continue except AttributeError : pass | Link services with their parent host | 208 | 6 |
19,679 | def linkify_s_by_sg ( self , servicegroups ) : for serv in self : new_servicegroups = [ ] if hasattr ( serv , 'servicegroups' ) and serv . servicegroups != '' : for sg_name in serv . servicegroups : sg_name = sg_name . strip ( ) servicegroup = servicegroups . find_by_name ( sg_name ) if servicegroup is not None : new_servicegroups . append ( servicegroup . uuid ) else : err = "Error: the servicegroup '%s' of the service '%s' is unknown" % ( sg_name , serv . get_dbg_name ( ) ) serv . add_error ( err ) serv . servicegroups = new_servicegroups | Link services with servicegroups | 167 | 5 |
19,680 | def clean ( self ) : to_del = [ ] for serv in self : if not serv . host : to_del . append ( serv . uuid ) for service_uuid in to_del : del self . items [ service_uuid ] | Remove services without host object linked to | 54 | 7 |
19,681 | def explode_services_from_hosts ( self , hosts , service , hnames ) : duplicate_for_hosts = [ ] # get the list of our host_names if more than 1 not_hosts = [ ] # the list of !host_name so we remove them after for hname in hnames : hname = hname . strip ( ) # If the name begin with a !, we put it in # the not list if hname . startswith ( '!' ) : not_hosts . append ( hname [ 1 : ] ) else : # the standard list duplicate_for_hosts . append ( hname ) # remove duplicate items from duplicate_for_hosts: duplicate_for_hosts = list ( set ( duplicate_for_hosts ) ) # Ok now we clean the duplicate_for_hosts with all hosts # of the not for hname in not_hosts : try : duplicate_for_hosts . remove ( hname ) except IndexError : pass # Now we duplicate the service for all host_names for hname in duplicate_for_hosts : host = hosts . find_by_name ( hname ) if host is None : service . add_error ( "Error: The hostname %s is unknown for the service %s!" % ( hname , service . get_name ( ) ) ) continue if host . is_excluded_for ( service ) : continue new_s = service . copy ( ) new_s . host_name = hname self . add_item ( new_s ) | Explodes a service based on a list of hosts . | 337 | 11 |
19,682 | def _local_create_service ( self , hosts , host_name , service ) : host = hosts . find_by_name ( host_name . strip ( ) ) if host . is_excluded_for ( service ) : return None # Creates a real service instance from the template new_s = service . copy ( ) new_s . host_name = host_name new_s . register = 1 self . add_item ( new_s ) return new_s | Create a new service based on a host_name and service instance . | 103 | 14 |
19,683 | def explode_services_from_templates ( self , hosts , service_template ) : hname = getattr ( service_template , "host_name" , None ) if not hname : logger . debug ( "Service template %s is declared without an host_name" , service_template . get_name ( ) ) return logger . debug ( "Explode services %s for the host: %s" , service_template . get_name ( ) , hname ) # Now really create the services if is_complex_expr ( hname ) : hnames = self . evaluate_hostgroup_expression ( hname . strip ( ) , hosts , hosts . templates , look_in = 'templates' ) for name in hnames : self . _local_create_service ( hosts , name , service_template ) else : hnames = [ n . strip ( ) for n in hname . split ( ',' ) if n . strip ( ) ] for hname in hnames : for name in hosts . find_hosts_that_use_template ( hname ) : self . _local_create_service ( hosts , name , service_template ) | Explodes services from templates . All hosts holding the specified templates are bound with the service . | 249 | 18 |
19,684 | def explode_services_duplicates ( self , hosts , service ) : hname = getattr ( service , "host_name" , None ) if hname is None : return # the generator case, we must create several new services # we must find our host, and get all key:value we need host = hosts . find_by_name ( hname . strip ( ) ) if host is None : service . add_error ( 'Error: The hostname %s is unknown for the service %s!' % ( hname , service . get_name ( ) ) ) return # Duplicate services for new_s in service . duplicate ( host ) : if host . is_excluded_for ( new_s ) : continue # Adds concrete instance self . add_item ( new_s ) | Explodes services holding a duplicate_foreach clause . | 170 | 11 |
19,685 | def register_service_into_servicegroups ( service , servicegroups ) : if hasattr ( service , 'service_description' ) : sname = service . service_description shname = getattr ( service , 'host_name' , '' ) if hasattr ( service , 'servicegroups' ) : # Todo: See if we can remove this if if isinstance ( service . servicegroups , list ) : sgs = service . servicegroups else : sgs = service . servicegroups . split ( ',' ) for servicegroup in sgs : servicegroups . add_member ( [ shname , sname ] , servicegroup . strip ( ) ) | Registers a service into the service groups declared in its servicegroups attribute . | 139 | 15 |
19,686 | def register_service_dependencies ( service , servicedependencies ) : # We explode service_dependencies into Servicedependency # We just create serviceDep with goods values (as STRING!), # the link pass will be done after sdeps = [ d . strip ( ) for d in getattr ( service , "service_dependencies" , [ ] ) ] # %2=0 are for hosts, !=0 are for service_description i = 0 hname = '' for elt in sdeps : if i % 2 == 0 : # host hname = elt else : # description desc = elt # we can register it (service) (depend on) -> (hname, desc) # If we do not have enough data for service, it'service no use if hasattr ( service , 'service_description' ) and hasattr ( service , 'host_name' ) : if hname == '' : hname = service . host_name servicedependencies . add_service_dependency ( service . host_name , service . service_description , hname , desc ) i += 1 | Registers a service dependencies . | 239 | 6 |
19,687 | def explode ( self , hosts , hostgroups , contactgroups , servicegroups , servicedependencies ) : # pylint: disable=too-many-locals # Then for every service create a copy of the service with just the host # because we are adding services, we can't just loop in it itemkeys = list ( self . items . keys ( ) ) for s_id in itemkeys : serv = self . items [ s_id ] # items::explode_host_groups_into_hosts # take all hosts from our hostgroup_name into our host_name property self . explode_host_groups_into_hosts ( serv , hosts , hostgroups ) # items::explode_contact_groups_into_contacts # take all contacts from our contact_groups into our contact property self . explode_contact_groups_into_contacts ( serv , contactgroups ) hnames = getattr ( serv , "host_name" , '' ) hnames = list ( set ( [ n . strip ( ) for n in hnames . split ( ',' ) if n . strip ( ) ] ) ) # hnames = strip_and_uniq(hnames) # We will duplicate if we have multiple host_name # or if we are a template (so a clean service) if len ( hnames ) == 1 : self . index_item ( serv ) else : if len ( hnames ) >= 2 : self . explode_services_from_hosts ( hosts , serv , hnames ) # Delete expanded source service, even if some errors exist self . remove_item ( serv ) for s_id in self . templates : template = self . templates [ s_id ] self . explode_contact_groups_into_contacts ( template , contactgroups ) self . explode_services_from_templates ( hosts , template ) # Explode services that have a duplicate_foreach clause duplicates = [ serv . uuid for serv in self if getattr ( serv , 'duplicate_foreach' , '' ) ] for s_id in duplicates : serv = self . items [ s_id ] self . explode_services_duplicates ( hosts , serv ) if not serv . configuration_errors : self . remove_item ( serv ) to_remove = [ ] for service in self : host = hosts . find_by_name ( service . host_name ) if host and host . is_excluded_for ( service ) : to_remove . append ( service ) for service in to_remove : self . remove_item ( service ) # Servicegroups property need to be fulfill for got the information # And then just register to this service_group for serv in self : self . register_service_into_servicegroups ( serv , servicegroups ) self . register_service_dependencies ( serv , servicedependencies ) | Explodes services from host hostgroups contactgroups servicegroups and dependencies . | 608 | 14 |
19,688 | def get_next_notif_time ( self , t_wished , status , creation_time , interval , escal_period ) : short_states = { u'WARNING' : 'w' , u'UNKNOWN' : 'u' , u'CRITICAL' : 'c' , u'RECOVERY' : 'r' , u'FLAPPING' : 'f' , u'DOWNTIME' : 's' , u'DOWN' : 'd' , u'UNREACHABLE' : 'u' , u'OK' : 'o' , u'UP' : 'o' } # If we are not time based, we bail out! if not self . time_based : return None # Check if we are valid if status in short_states and short_states [ status ] not in self . escalation_options : return None # Look for the min of our future validity start = self . first_notification_time * interval + creation_time # If we are after the classic next time, we are not asking for a smaller interval if start > t_wished : return None # Maybe the time we found is not a valid one.... if escal_period is not None and not escal_period . is_time_valid ( start ) : return None # Ok so I ask for my start as a possibility for the next notification time return start | Get the next notification time for the escalation Only legit for time based escalation | 297 | 14 |
19,689 | def linkify_es_by_s ( self , services ) : for escalation in self : # If no host, no hope of having a service if not hasattr ( escalation , 'host_name' ) : continue es_hname , sdesc = escalation . host_name , escalation . service_description if not es_hname . strip ( ) or not sdesc . strip ( ) : continue for hname in strip_and_uniq ( es_hname . split ( ',' ) ) : if sdesc . strip ( ) == '*' : slist = services . find_srvs_by_hostname ( hname ) if slist is not None : slist = [ services [ serv ] for serv in slist ] for serv in slist : serv . escalations . append ( escalation . uuid ) else : for sname in strip_and_uniq ( sdesc . split ( ',' ) ) : serv = services . find_srv_by_name_and_hostname ( hname , sname ) if serv is not None : serv . escalations . append ( escalation . uuid ) | Add each escalation object into service . escalation attribute | 242 | 9 |
19,690 | def linkify_es_by_h ( self , hosts ) : for escal in self : # If no host, no hope of having a service if ( not hasattr ( escal , 'host_name' ) or escal . host_name . strip ( ) == '' or ( hasattr ( escal , 'service_description' ) and escal . service_description . strip ( ) != '' ) ) : continue # I must be NOT a escalation on for service for hname in strip_and_uniq ( escal . host_name . split ( ',' ) ) : host = hosts . find_by_name ( hname ) if host is not None : host . escalations . append ( escal . uuid ) | Add each escalation object into host . escalation attribute | 151 | 9 |
19,691 | def explode ( self , hosts , hostgroups , contactgroups ) : for i in self : # items::explode_host_groups_into_hosts # take all hosts from our hostgroup_name into our host_name property self . explode_host_groups_into_hosts ( i , hosts , hostgroups ) # items::explode_contact_groups_into_contacts # take all contacts from our contact_groups into our contact property self . explode_contact_groups_into_contacts ( i , contactgroups ) | Loop over all escalation and explode hostsgroups in host and contactgroups in contacts | 114 | 15 |
19,692 | def get_hosts_by_explosion ( self , hostgroups ) : # pylint: disable=access-member-before-definition # First we tag the hg so it will not be explode # if a son of it already call it self . already_exploded = True # Now the recursive part # rec_tag is set to False every HG we explode # so if True here, it must be a loop in HG # calls... not GOOD! if self . rec_tag : logger . error ( "[hostgroup::%s] got a loop in hostgroup definition" , self . get_name ( ) ) return self . get_hosts ( ) # Ok, not a loop, we tag it and continue self . rec_tag = True hg_mbrs = self . get_hostgroup_members ( ) for hg_mbr in hg_mbrs : hostgroup = hostgroups . find_by_name ( hg_mbr . strip ( ) ) if hostgroup is not None : value = hostgroup . get_hosts_by_explosion ( hostgroups ) if value is not None : self . add_members ( value ) return self . get_hosts ( ) | Get hosts of this group | 261 | 5 |
19,693 | def add_member ( self , host_name , hostgroup_name ) : hostgroup = self . find_by_name ( hostgroup_name ) if not hostgroup : hostgroup = Hostgroup ( { 'hostgroup_name' : hostgroup_name , 'alias' : hostgroup_name , 'members' : host_name } ) self . add ( hostgroup ) else : hostgroup . add_members ( host_name ) | Add a host string to a hostgroup member if the host group do not exist create it | 95 | 18 |
19,694 | def linkify ( self , hosts = None , realms = None , forced_realms_hostgroups = True ) : self . linkify_hostgroups_hosts ( hosts ) self . linkify_hostgroups_realms_hosts ( realms , hosts , forced_realms_hostgroups ) | Link hostgroups with hosts and realms | 64 | 7 |
19,695 | def linkify_hostgroups_hosts ( self , hosts ) : for hostgroup in self : members = hostgroup . get_hosts ( ) # The new members identifiers list new_members = [ ] for member in members : # member is an host name member = member . strip ( ) if not member : # void entry, skip this continue if member == '*' : # All the hosts identifiers list new_members . extend ( list ( hosts . items . keys ( ) ) ) else : host = hosts . find_by_name ( member ) if host is not None : new_members . append ( host . uuid ) if hostgroup . uuid not in host . hostgroups : host . hostgroups . append ( hostgroup . uuid ) else : hostgroup . add_unknown_members ( member ) # Make members unique new_members = list ( set ( new_members ) ) # We find the id, we replace the names hostgroup . replace_members ( new_members ) | We just search for each hostgroup the id of the hosts and replace the names by the found identifiers | 211 | 20 |
19,696 | def explode ( self ) : # We do not want a same hostgroup to be exploded again and again # so we tag it for tmp_hg in list ( self . items . values ( ) ) : tmp_hg . already_exploded = False for hostgroup in list ( self . items . values ( ) ) : if hostgroup . already_exploded : continue # get_hosts_by_explosion is a recursive # function, so we must tag hg so we do not loop for tmp_hg in list ( self . items . values ( ) ) : tmp_hg . rec_tag = False hostgroup . get_hosts_by_explosion ( self ) # We clean the tags for tmp_hg in list ( self . items . values ( ) ) : if hasattr ( tmp_hg , 'rec_tag' ) : del tmp_hg . rec_tag del tmp_hg . already_exploded | Fill members with hostgroup_members | 205 | 7 |
19,697 | def run ( self ) : def _started_callback ( ) : """Callback function when Cherrypy Engine is started""" cherrypy . log ( "CherryPy engine started and listening..." ) self . cherrypy_thread = None try : cherrypy . log ( "Starting CherryPy engine on %s" % ( self . uri ) ) self . cherrypy_thread = cherrypy . engine . start_with_callback ( _started_callback ) cherrypy . engine . block ( ) cherrypy . log ( "Exited from the engine block" ) except socket . error as exp : raise PortNotFree ( "Error: Sorry, the HTTP server did not started correctly: error: %s" % ( str ( exp ) ) ) | Wrapper to start the CherryPy server | 154 | 8 |
19,698 | def stop ( self ) : # pylint: disable=no-self-use cherrypy . log ( "Stopping CherryPy engine (current state: %s)..." % cherrypy . engine . state ) try : cherrypy . engine . exit ( ) except RuntimeWarning : pass except SystemExit : cherrypy . log ( 'SystemExit raised: shutting down bus' ) cherrypy . log ( "Stopped" ) | Wrapper to stop the CherryPy server | 89 | 8 |
19,699 | def create_queues ( self , manager = None ) : self . clear_queues ( manager ) # If no Manager() object, go with classic Queue() if not manager : self . from_q = Queue ( ) self . to_q = Queue ( ) else : self . from_q = manager . Queue ( ) self . to_q = manager . Queue ( ) | Create the shared queues that will be used by alignak daemon process and this module process . But clear queues if they were already set before recreating new one . | 85 | 32 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.