コード例 #1
0
def upgrade_to_version_2_4():
    """ Upgrade to version 2.4
    We will adapt to the following removals:
    * hostgroup cisco-hostgroup
    * servicegroup proliant-services
    * contactgroup proliant-contacts
    * servicegroup eva-services
    * contactgroup eva-contacts
    * servicegroup windows-services
    * servicegroup linux-services
    * servicegroup mssql-services
    """
    print("Upgrading to config version 2.4 ...", end=' ')
    dest_file = okconfig.config.destination_directory + "/backwards-compatibility.cfg"
    hostgroups = ['cisco-hostgroup']
    servicegroups = [
        'proliant-services', 'eva-services', 'windows-services',
        'linux-services', 'mssql-services'
    ]
    contactgroups = ['proliant-contacts', 'eva-contacts']
    for i in hostgroups:
        hg = Model.Hostgroup.objects.filter(hostgroup_name=i)
        hg_hosts = Model.Host.objects.filter(host_groups__has_field=i)
        if hg_hosts and not hg:
            h = Model.Hostgroup()
            h['hostgroup_name'] = i
            h['alias'] = i
            h.set_filename(dest_file)
            h.save()
            print("Created hostgroup", i)
    for i in servicegroups:
        sg = Model.Servicegroup.objects.filter(servicegroup_name=i)
        sg_services = Model.Service.objects.filter(service_groups__has_field=i)
        if sg_services and not sg:
            s = Model.Servicegroup()
            s['servicegroup_name'] = i
            s['alias'] = i
            s.set_filename(dest_file)
            s.save()
            print("Created servicegroup", i)
    for i in contactgroups:
        cg = Model.Contactgroup.objects.filter(contactgroup_name=i)
        cg_contacts = Model.Contact.objects.filter(contactgroups__has_field=i)
        cg_hosts = Model.Host.objects.filter(contact_groups__has_field=i)
        cg_services = Model.Host.objects.filter(contact_groups__has_field=i)
        if not cg and (cg_contacts or cg_hosts or cg_services):
            c = Model.Contactgroup()
            c['contactgroup_name'] = i
            c['alias'] = i
            c.set_filename(dest_file)
            c.save()
            print("Created contactgroup", i)
    print("ok")
コード例 #2
0
def add_host(host_name=None, alias=None, address=None, use=None, **kwargs):
    """
    增加一个nagios主机,增加后重启nagios进程
    @host_name 主机名
    @alias 主机的别名
    @address 主机的IP地址
    @use 主机使用的模板,如不指定,默认使用generic-host
    """
    if os.getuid() != 0:
        return False, RuntimeError("need root privileges.")
    
    if not address or not host_name:
        return False, RuntimeError("address or host_name is empty.")
    
    if not alias:
        alias = host_name
    
    if not use:
        use = "generic-host"
    
    if get_host_by_address(address):
        return False, RuntimeError("address is duplicate!.")
    
    if host_name and address:
        filename = NAGIOS_CONF_DIR + address + "_" + host_name + ".cfg"
        
    new_host = Model.Host(filename=filename, **kwargs)
    new_host.host_name = host_name
    new_host.alias = alias
    new_host.address = address
    new_host.use = use
    
    new_host.save()
    return True, None
コード例 #3
0
ファイル: forms.py プロジェクト: ppepos/adagios
 def __init__(self, *args, **kwargs):
     super(AdagiosForm, self).__init__(*args, **kwargs)
     self.pynag_object = Model.Service()
     self.fields['host_name'] = self.get_pynagField('host_name')
     self.fields['service_description'] = self.get_pynagField(
         'service_description')
     self.fields['check_command'] = self.get_pynagField('check_command')
コード例 #4
0
    def add_host(self,
                 group_name,
                 host_name,
                 alias,
                 address,
                 sync=True,
                 **kwargs):
        host = self.get_host(host_name)
        if host:
            return Result(1, "host is already exists")
        group = self.get_hostgroup(group_name)
        if not group:
            return Result(1, "host group is not exists")

        host = Model.Host()
        host.set_filename("{0}/{1}.cfg".format(self.nagios_host_cfg_dir,
                                               host_name))
        host.host_name = host_name
        host.alias = alias
        host.address = address
        host.notifications_enabled = kwargs.pop('notifications_enabled', 0)
        for _k, _v in kwargs.items():
            if hasattr(host, _k) and _v:
                setattr(host, _k, _v)
        host.save()
        host.add_to_hostgroup(group_name)
        if sync:
            self.reload_nagios()
        return _success
コード例 #5
0
    def __init__(self, service=Model.Service(), *args, **kwargs):
        self.service = service
        super(forms.Form, self).__init__(*args, **kwargs)

        # Run through all the all attributes. Add
        # to form everything that starts with "_"
        self.description = service['service_description']
        fieldname = "%s::%s::%s" % (service['host_name'],
                                    service['service_description'], 'register')
        self.fields[fieldname] = forms.BooleanField(
            required=False,
            initial=service['register'] == "1",
            label='register')
        self.register = fieldname

        macros = []
        self.command_line = None
        try:
            self.command_line = service.get_effective_command_line()
            for macro, value in service.get_all_macros().items():
                if macro.startswith('$_SERVICE') or macro.startswith('S$ARG'):
                    macros.append(macro)
            for k in sorted(macros):
                fieldname = "%s::%s::%s" % (service['host_name'],
                                            service['service_description'], k)
                label = k.replace('$_SERVICE', '')
                label = label.replace('_', ' ')
                label = label.replace('$', '')
                label = label.capitalize()
                self.fields[fieldname] = forms.CharField(
                    required=False, initial=service.get_macro(k), label=label)
        # KeyError can occur if service has an invalid check_command
        except KeyError:
            pass
コード例 #6
0
def addservice(request):
    c = {}
    c.update(csrf(request))
    c['form'] = forms.AddServiceToHostForm()
    c['messages'] = []
    c['errors'] = []
    c['filename'] = Model.config.cfg_file
    if request.method == 'POST':
        c['form'] = form = forms.AddServiceToHostForm(data=request.POST)
        if form.is_valid():
            host_name = form.cleaned_data['host_name']
            host = Model.Host.objects.get_by_shortname(host_name)
            service = form.cleaned_data['service']
            new_service = Model.Service()
            new_service.host_name = host_name
            new_service.use = service
            new_service.set_filename(host.get_filename())
            #new_service.reload_object()
            c['my_object'] = new_service

            # Add custom macros if any were specified
            for k, v in form.data.items():
                if k.startswith("_") or k.startswith('service_description'):
                    new_service[k] = v
            try:
                new_service.save()
                return HttpResponseRedirect(
                    reverse('objectbrowser.views.edit_object',
                            kwargs={'object_id': new_service.get_id()}))
            except IOError, e:
                c['errors'].append(e)
        else:
            c['errors'].append("Could not validate form")
コード例 #7
0
def set_maincfg_attribute(attribute, new_value, old_value='None', append=False):
    """ Sets specific configuration values of nagios.cfg

        Required Arguments:
                attribute   -- Attribute to change (i.e. process_performance_data)
                new_value   -- New value for the attribute (i.e. "1")

        Optional Arguments:
                old_value   -- Specify this to change specific value
                filename    -- Configuration file to modify (i.e. /etc/nagios/nagios.cfg)
                append      -- Set to 'True' to append a new configuration attribute
        Returns:
                True	-- If any changes were made
                False	-- If no changes were made
        """
    filename = Model.config.cfg_file
    if old_value.lower() == 'none':
        old_value = None
    if new_value.lower() == 'none':
        new_value = None
    if filename.lower() == 'none':
        filename = None
    if append.lower() == 'false':
        append = False
    elif append.lower() == 'true':
        append = True
    elif append.lower() == 'none':
        append = None
    return Model._edit_static_file(attribute=attribute, new_value=new_value, old_value=old_value, filename=filename, append=append)
コード例 #8
0
def split_line(text):
    # skip the comment lines
    if text[0] == "#":
        return
    # explode it
    explode_list = text.strip().split('|')
    #	print len(explode_list)
    # try to identify each field
    # raise an exception if, on each line, we don't have at least 5 fields
    try:
        # get the frequency
        frequency = explode_list[1]
        # get the options
        options = explode_list[2]
        # get the command
        command = explode_list[3]
        # get the service description
        service = explode_list[4]
    except IndexError as idx_e:
        sys.stderr.write(
            "A field is missing in the configuration file, on the following line:\n"
        )
        sys.stderr.write(text)
        sys.exit(1)
    # we accept empty values only for option field
    if command == "" or service == "":
        sys.stderr.write(
            "An empty field is now allowed on command, service.\n")
        sys.exit(1)
    # target is in comma separated list, explode it
    host_list = explode_list[0].strip().split(',')

    # set icinga configuration file
    Model.cfg_file = icinga_conf
    # for each host or host_group in this configuration line
    for idx, host in enumerate(host_list):
        # create a new service object
        s = Model.Service()
        # Set some attributes for the service
        s.service_description = service
        s.use = 'generic-service'
        #		s.register = 'register'
        if frequency != '':
            s.check_interval = frequency
        s.check_command = command
        #		s.notification_options = 'y'
        if host[0] == "@":
            s.hostgroup_name = host[1:]
        else:
            s.host_name = host
        if options == "passive":
            s.passive_checks_enabled = '1'
        # put it into an array
        service_array.append(s)
コード例 #9
0
def get_pynag_service(target_id, service_name):
    services = Model.Service.objects.filter(host_name=target_id,
                                            service_description=service_name)
    if len(services) == 0:
        service = Model.Service()
        service.set_filename(CHARM_CFG)
        service.set_attribute('service_description', service_name)
        service.set_attribute('host_name', target_id)
        service.set_attribute('use', 'generic-service')
    else:
        service = services[0]
    return service
コード例 #10
0
ファイル: windows.py プロジェクト: buggtb/nagios-charm
def update_host(target_id, charm_cfg):
    host = Model.Host()
    host.set_filename(charm_cfg)
    host.set_attribute('host_name', target_id)
    host.set_attribute('use', 'generic-host')
    # Adding the windows icon image definitions to the host.
    host.set_attribute('icon_image', 'base/win40.png')
    host.set_attribute('icon_image_alt', 'Windows')
    host.set_attribute('vrml_image', 'win40.png')
    host.set_attribute('statusmap_image', 'base/win40.gd2')
    host.save()
    host = Model.Host.objects.get_by_shortname(target_id)
    return host
コード例 #11
0
 def add_hostgroup(self, name, alias, members=None, sync=True):
     grp = self.get_hostgroup(name)
     if grp:
         return Result(1, u"host group is already exists")
     grp = Model.Hostgroup()
     grp.set_filename(self.nagios_host_group_cfg)
     grp.hostgroup_name = name
     grp.alias = alias
     if members:
         grp.members = members
     grp.save()
     if sync:
         self.reload_nagios()
     return _success
コード例 #12
0
    def writeHost(self, host):
        if host[CHANGE_MODE] == CHANGE_MODE_REMOVE:
            hostModel = Model.Host.objects.filter(host_name=host['host_name'])
            if hostModel:
                hostModel[0].delete(recursive=True)
            return
        if host[CHANGE_MODE] == CHANGE_MODE_ADD:
            hostModel = Model.Host()
            hostModel = self.fillModel(hostModel, host)
            hostModel.set_filename(self.getCfgFileName(host['host_name']))
            hostModel.save()

        if host.get(HOST_SERVICES):
            self.writeHostServices(host)
コード例 #13
0
 def writeHostGroup(self, hostgroup):
     changeMode = hostgroup[CHANGE_MODE]
     if changeMode == CHANGE_MODE_ADD:
         hostgroupModel = Model.Hostgroup()
         hostgroupModel['hostgroup_name'] = hostgroup['hostgroup_name']
         hostgroupModel['alias'] = hostgroup['alias']
         hostgroupModel.set_filename(
             self.getCfgFileName(hostgroup['hostgroup_name']))
         hostgroupModel.save()
     # Process all the hosts in the hostgroup. ChangeMode of the hostgroup
     # will be used to proces the host if there is not changeMode specified
     # in the host.
     if hostgroup['_hosts']:
         self.writeHosts(hostgroup['_hosts'], changeMode)
コード例 #14
0
def main():

    module = AnsibleModule(
        argument_spec = dict(
            configpath        = dict(required=True, type='str'),
            host_name         = dict(required=False, type='str'),
            service           = dict(required=False, type='str'),
            contact           = dict(required=False, type='str'),
            replace           = dict(required=False, default=False, type='bool'),
            values            = dict(required=True, type='dict'),
        ),
        add_file_common_args=True,
        supports_check_mode=True,
    )

    host_name = module.params['host_name']
    configpath = module.params['configpath']
    replaceall = module.params['replace']
    response = {}

    if not os.path.exists(configpath):
        module.fail_json(msg="Nagios config %s not found" % (configpath))

    Model.cfg_file = configpath

    changed = False
    curhost = None
    if host_name :
       host = Model.Host.objects.filter(host_name=host_name)
       if host and replaceall:
          curhost = host[0]
          for i in curhost.keys():
             if i not in ['meta','id']:
                curhost[i] = None
       else:
          curhost = Model.Host()
          curhost.use = 'New hosts go in a pynag/hosts folder need to fix this'
          
       for key, value in module.params['values'].iteritems():
          changed = True
          curhost[key] = value 
          pass
          
    if not module.check_mode:
        # Save here if not check mode
        curhost.save()
        pass

    module.exit_json(meta=response)
コード例 #15
0
def _make_check_command(args):
    args = [str(arg) for arg in args]
    # There is some worry of collision, but the uniqueness of the initial
    # command should be enough.
    signature = reduce_RE.sub('_',
                              ''.join([os.path.basename(arg) for arg in args]))
    Model.Command.objects.reload_cache()
    try:
        cmd = Model.Command.objects.get_by_shortname(signature)
    except (ValueError, KeyError):
        cmd = Model.Command()
        cmd.set_attribute('command_name', signature)
        cmd.set_attribute('command_line', ' '.join(args))
        cmd.save()
    return signature
コード例 #16
0
 def writeService(self, service, hostname):
     if service[CHANGE_MODE] == CHANGE_MODE_ADD:
         serviceModel = Model.Service()
         serviceModel = self.fillModel(serviceModel, service)
         serviceModel.set_filename(self.getCfgFileName(hostname))
         serviceModel[GENERATED_BY_AUTOCONFIG] = 1
         serviceModel.save()
     elif service[CHANGE_MODE] == CHANGE_MODE_REMOVE:
         serviceModel = Model.Service.objects.filter(
             host_name=hostname,
             service_description=service['service_description'])
         if serviceModel:
             serviceModel[0].delete()
     elif service[CHANGE_MODE] == CHANGE_MODE_UPDATE:
         serviceModel = server_utils.getServiceConfig(
             service['service_description'], service['host_name'])
         self.fillModel(serviceModel, service)
         serviceModel.save()
コード例 #17
0
def refresh_hostgroups():
    """ Not the most efficient thing but since we're only
        parsing what is already on disk here its not too bad """
    hosts = [x['host_name'] for x in Model.Host.objects.all if x['host_name']]

    hgroups = {}
    for host in hosts:
        try:
            (service, unit_id) = host.rsplit('-', 1)
        except ValueError:
            continue
        if service in hgroups:
            hgroups[service].append(host)
        else:
            hgroups[service] = [host]

    # Find existing autogenerated
    auto_hgroups = Model.Hostgroup.objects.filter(
        notes__contains='#autogenerated#')
    auto_hgroups = [x.get_attribute('hostgroup_name') for x in auto_hgroups]

    # Delete the ones not in hgroups
    to_delete = set(auto_hgroups).difference(set(hgroups.keys()))
    for hgroup_name in to_delete:
        try:
            hgroup = Model.Hostgroup.objects.get_by_shortname(hgroup_name)
            hgroup.delete()
        except (ValueError, KeyError):
            pass

    for hgroup_name, members in hgroups.iteritems():
        try:
            hgroup = Model.Hostgroup.objects.get_by_shortname(hgroup_name)
        except (ValueError, KeyError):
            hgroup = Model.Hostgroup()
            hgroup.set_filename(CHARM_CFG)
            hgroup.set_attribute('hostgroup_name', hgroup_name)
            hgroup.set_attribute('notes', '#autogenerated#')

        hgroup.set_attribute('members', ','.join(members))
        hgroup.save()
コード例 #18
0
 def add_service(self,
                 host_name,
                 serv_desc,
                 check_command,
                 sync=True,
                 **kwargs):
     service = Model.Service()
     service.use = kwargs.pop("use")
     service.host_name = host_name
     service.service_description = serv_desc
     service.check_command = check_command
     service.notifications_enabled = kwargs.pop('notifications_enabled', 0)
     service.process_perf_data = kwargs.pop("process_perf_data", 1)
     service.max_check_attempts = kwargs.pop("max_check_attempts", 1)
     service.normal_check_interval = kwargs.pop("normal_check_interval", 5)
     service.retry_check_interval = kwargs.pop("retry_check_interval", 1)
     for _k, _v in kwargs.items():
         if hasattr(service, _k) and _v:
             setattr(service, _k, _v)
     service.save()
     if sync:
         self.reload_nagios()
     return _success
コード例 #19
0
 def add_contact(self,
                 name,
                 alias,
                 email,
                 contactgroup,
                 sync=True,
                 **kwargs):
     contact = self.get_contact(name)
     if contact:
         return Result(1, u"contact is already exists")
     contact = Model.Contact()
     contact.set_filename(self.nagios_contact_cfg)
     contact.use = 'generic-contact'
     contact.contact_name = name
     contact.alias = alias
     contact.email = email
     if 'pager' in kwargs:
         contact.pager = kwargs.pop("pager")
     contact.save()
     contact.add_to_contactgroup(contactgroup)
     if sync:
         self.reload_nagios()
     return _success
コード例 #20
0
def add_service(address=None, service_description=None, use=None, check_command=None, filename=None, **kwargs):
    """
    为主机增加服务,增加配置文件后,重启nagios进程
    @address 主机IP地址
    @service_description 服务的描述
    @check_command 要执行的检测命令
    @filename 主机的配置文件名
    """
    if os.getuid() != 0:
        return False, RuntimeError("need root privileges.")
    
    if not use:
        use = "generic-service"
    
    host = get_host_by_address(address)
    if not host:
        return False, RuntimeError("can not find any host.")
    
    if not filename:
        filename = host.get_filename()
    
    if not service_description or not check_command:
        return False, RuntimeError("missed argument.")

    new_service = Model.Service(filename=filename, **kwargs)
    new_service.service_description = service_description
    new_service.use = use
    new_service.check_command = check_command
    new_service.host_name = host.host_name
    new_service.save()
    
    _, err = restart_nagios_process()
    if err != None:
        raise err
    
    return True, None
コード例 #21
0
 def __init__(self, service=Model.Service(), *args, **kwargs):
     super(forms.Form, self).__init__(*args, **kwargs)
     self.fields['host_name'].choices = get_all_hosts()
     self.fields['service'].choices = get_inactive_services()
コード例 #22
0
 def save(self):
     from pynag import Model
     perfdata = self.cleaned_data['perfdata']
     perfdata = Model.PerfData(perfdata)
     self.results = perfdata.metrics
コード例 #23
0
            exit(1)

        apply_dict = json.loads(argv[2])

        with open(FILE_PATH_CHECK_SCRIPT, 'w') as fh_cs:
            fh_cs.write(SCRIPT_TINKERFORGE_CHECK)

        os.chmod(FILE_PATH_CHECK_SCRIPT,
                 stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH | \
                 stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)

        if os.path.isfile(FILE_PATH_TF_NAGIOS_CONFIGURATION):
            os.remove(FILE_PATH_TF_NAGIOS_CONFIGURATION)

        for rule in apply_dict['rules']:
            tf_command = Model.Command()
            tf_service = Model.Service()
            tf_command.set_filename(FILE_PATH_TF_NAGIOS_CONFIGURATION)
            tf_service.set_filename(FILE_PATH_TF_NAGIOS_CONFIGURATION)
            tf_command.command_name = rule['check_command']
            tf_command.command_line = rule['command_line']
            tf_service.use                      = 'generic-service'
            tf_service.host_name                = 'localhost'
            tf_service.service_description      = rule['service_description']
            tf_service.check_command            = rule['check_command']
            tf_service.max_check_attempts       = '4'
            tf_service.check_interval           = '1'
            tf_service.retry_interval           = '1'
            tf_service.check_period             = '24x7'
            tf_service.notification_interval    = '5'
            tf_service.first_notification_delay = '0'