nagios 29.8 KB
Newer Older
1 2 3 4 5 6 7
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is largely copied from the Nagios module included in the
# Func project. Original copyright follows:
#
# func-nagios - Schedule downtime and enables/disable notifications
8
# Copyright 2011, Red Hat, Inc.
9 10 11 12 13 14 15 16 17
# Tim Bielawa <tbielawa@redhat.com>
#
# This software may be freely redistributed under the terms of the GNU
# general public license version 2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.


18 19 20
DOCUMENTATION = '''
---
module: nagios
21
short_description: Perform common tasks in Nagios related to downtime and notifications.
22
description:
23
  - "The M(nagios) module has two basic functions: scheduling downtime and toggling alerts for services or hosts."
24
  - All actions require the I(host) parameter to be given explicitly. In playbooks you can use the C({{inventory_hostname}}) variable to refer to the host the playbook is currently running on.
25
  - You can specify multiple services at once by separating them with commas, .e.g., C(services=httpd,nfs,puppet).
26
  - When specifying what service to handle there is a special service value, I(host), which will handle alerts/downtime for the I(host itself), e.g., C(service=host). This keyword may not be given with other services at the same time. I(Setting alerts/downtime for a host does not affect alerts/downtime for any of the services running on it.) To schedule downtime for all services on particular host use keyword "all", e.g., C(service=all).
Jan-Piet Mens committed
27
  - When using the M(nagios) module you will need to specify your Nagios server using the C(delegate_to) parameter.
28
version_added: "0.7"
29 30 31 32 33 34
options:
  action:
    description:
      - Action to take.
    required: true
    default: null
35 36
    choices: [ "downtime", "enable_alerts", "disable_alerts", "silence", "unsilence",
               "silence_nagios", "unsilence_nagios", "command" ]
37 38 39
  host:
    description:
      - Host to operate on in Nagios.
40
    required: false
41 42 43 44
    default: null
  cmdfile:
    description:
      - Path to the nagios I(command file) (FIFO pipe).
45
        Only required if auto-detection fails.
46 47 48 49 50
    required: false
    default: auto-detected
  author:
    description:
     - Author to leave downtime comments as.
51
       Only usable with the C(downtime) action.
52 53 54 55 56
    required: false
    default: Ansible
  minutes:
    description:
      - Minutes to schedule downtime for.
Jan-Piet Mens committed
57
      - Only usable with the C(downtime) action.
58 59 60 61 62
    required: false
    default: 30
  services:
    description:
      - What to manage downtime/alerts for. Separate multiple services with commas.
63 64
        C(service) is an alias for C(services).
        B(Required) option when using the C(downtime), C(enable_alerts), and C(disable_alerts) actions.
65
    aliases: [ "service" ]
66 67
    required: true
    default: null
68 69
  command:
    description:
70 71 72
      - The raw command to send to nagios, which
        should not include the submitted time header or the line-feed
        B(Required) option when using the C(command) action.
73 74 75
    required: true
    default: null

76
author: Tim Bielawa
77
requirements: [ "Nagios" ]
78 79 80 81 82 83 84
'''

EXAMPLES = '''
# set 30 minutes of apache downtime
- nagios: action=downtime minutes=30 service=httpd host={{ inventory_hostname }}

# schedule an hour of HOST downtime
85
- nagios: action=downtime minutes=60 service=host host={{ inventory_hostname }}
86 87

# schedule downtime for ALL services on HOST
88
- nagios: action=downtime minutes=45 service=all host={{ inventory_hostname }}
89 90

# schedule downtime for a few services
91
- nagios: action=downtime services=frob,foobar,qeuz host={{ inventory_hostname }}
92 93

# enable SMART disk alerts
94
- nagios: action=enable_alerts service=smart host={{ inventory_hostname }}
95 96

# "two services at once: disable httpd and nfs alerts"
97
- nagios: action=disable_alerts service=httpd,nfs host={{ inventory_hostname }}
98 99

# disable HOST alerts
100
- nagios: action=disable_alerts service=host host={{ inventory_hostname }}
101 102

# silence ALL alerts
103
- nagios: action=silence host={{ inventory_hostname }}
104 105

# unsilence all alerts
106
- nagios: action=unsilence host={{ inventory_hostname }}
107 108 109 110 111 112 113 114 115

# SHUT UP NAGIOS
- nagios: action=silence_nagios

# ANNOY ME NAGIOS
- nagios: action=unsilence_nagios

# command something
- nagios: action=command command='DISABLE_FAILURE_PREDICTION'
116 117
'''

118 119 120
import ConfigParser
import types
import time
121
import os.path
122 123 124 125 126

######################################################################


def which_cmdfile():
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    locations = [
        # rhel
        '/etc/nagios/nagios.cfg',
        # debian
        '/etc/nagios3/nagios.cfg',
        # older debian
        '/etc/nagios2/nagios.cfg',
        # bsd, solaris
        '/usr/local/etc/nagios/nagios.cfg',
        # groundwork it monitoring
        '/usr/local/groundwork/nagios/etc/nagios.cfg',
        # open monitoring distribution
        '/omd/sites/oppy/tmp/nagios/nagios.cfg',
        # ???
        '/usr/local/nagios/etc/nagios.cfg',
        '/usr/local/nagios/nagios.cfg',
        '/opt/nagios/etc/nagios.cfg',
144 145 146 147 148
        '/opt/nagios/nagios.cfg',
        # icinga on debian/ubuntu
        '/etc/icinga/icinga.cfg',
        # icinga installed from source (default location)
        '/usr/local/icinga/etc/icinga.cfg',
149 150 151 152 153 154
        ]

    for path in locations:
        if os.path.exists(path):
            for line in open(path):
                if line.startswith('command_file'):
155
                    return line.split('=')[1].strip()
156

157
    return None
158 159 160 161 162 163 164 165 166 167

######################################################################


def main():
    ACTION_CHOICES = [
        'downtime',
        'silence',
        'unsilence',
        'enable_alerts',
168 169 170 171
        'disable_alerts',
        'silence_nagios',
        'unsilence_nagios',
        'command',
172 173 174 175 176 177
        ]

    module = AnsibleModule(
        argument_spec=dict(
            action=dict(required=True, default=None, choices=ACTION_CHOICES),
            author=dict(default='Ansible'),
178
            host=dict(required=False, default=None),
179 180 181
            minutes=dict(default=30),
            cmdfile=dict(default=which_cmdfile()),
            services=dict(default=None, aliases=['service']),
182
            command=dict(required=False, default=None),
183 184 185 186
            )
        )

    action = module.params['action']
187
    host = module.params['host']
188 189
    minutes = module.params['minutes']
    services = module.params['services']
190
    cmdfile = module.params['cmdfile']
191 192
    command = module.params['command']
    
193 194 195 196 197
    ##################################################################
    # Required args per action:
    # downtime = (minutes, service, host)
    # (un)silence = (host)
    # (enable/disable)_alerts = (service, host)
198
    # command = command
199 200 201 202 203
    #
    # AnsibleModule will verify most stuff, we need to verify
    # 'minutes' and 'service' manually.

    ##################################################################
204 205 206 207
    if action not in ['command', 'silence_nagios', 'unsilence_nagios']:
        if not host:
            module.fail_json(msg='no host specified for action requiring one')
    ######################################################################
208 209 210 211 212 213 214 215 216
    if action == 'downtime':
        # Make sure there's an actual service selected
        if not services:
            module.fail_json(msg='no service selected to set downtime for')
        # Make sure minutes is a number
        try:
            m = int(minutes)
            if not isinstance(m, types.IntType):
                module.fail_json(msg='minutes must be a number')
217
        except Exception:
218 219 220 221 222 223 224
            module.fail_json(msg='invalid entry for minutes')

    ##################################################################
    if action in ['enable_alerts', 'disable_alerts']:
        if not services:
            module.fail_json(msg='a service is required when setting alerts')

225 226 227
    if action in ['command']:
        if not command:
            module.fail_json(msg='no command passed for command action')
228
    ##################################################################
229 230 231 232
    if not cmdfile:
        module.fail_json('unable to locate nagios.cfg')

    ##################################################################
233
    ansible_nagios = Nagios(module, **module.params)
234
    if module.check_mode:
235 236 237
        module.exit_json(changed=True)
    else:
        ansible_nagios.act()
238 239
    ##################################################################

240

241
######################################################################
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
class Nagios(object):
    """
    Perform common tasks in Nagios related to downtime and
    notifications.

    The complete set of external commands Nagios handles is documented
    on their website:

    http://old.nagios.org/developerinfo/externalcommands/commandlist.php

    Note that in the case of `schedule_svc_downtime`,
    `enable_svc_notifications`, and `disable_svc_notifications`, the
    service argument should be passed as a list.
    """

    def __init__(self, module, **kwargs):
        self.module = module
        self.action = kwargs['action']
        self.author = kwargs['author']
        self.host = kwargs['host']
        self.minutes = int(kwargs['minutes'])
        self.cmdfile = kwargs['cmdfile']
264
        self.command = kwargs['command']
265

266
        if (kwargs['services'] is None) or (kwargs['services'] == 'host') or (kwargs['services'] == 'all'):
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
            self.services = kwargs['services']
        else:
            self.services = kwargs['services'].split(',')

        self.command_results = []

    def _now(self):
        """
        The time in seconds since 12:00:00AM Jan 1, 1970
        """

        return int(time.time())

    def _write_command(self, cmd):
        """
        Write the given command to the Nagios command file
        """

        try:
286
            fp = open(self.cmdfile, 'w')
287 288 289 290 291
            fp.write(cmd)
            fp.flush()
            fp.close()
            self.command_results.append(cmd.strip())
        except IOError:
292 293
            self.module.fail_json(msg='unable to write to nagios command file',
                                  cmdfile=self.cmdfile)
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341

    def _fmt_dt_str(self, cmd, host, duration, author=None,
                    comment="Scheduling downtime", start=None,
                    svc=None, fixed=1, trigger=0):
        """
        Format an external-command downtime string.

        cmd - Nagios command ID
        host - Host schedule downtime on
        duration - Minutes to schedule downtime for
        author - Name to file the downtime as
        comment - Reason for running this command (upgrade, reboot, etc)
        start - Start of downtime in seconds since 12:00AM Jan 1 1970
          Default is to use the entry time (now)
        svc - Service to schedule downtime for, omit when for host downtime
        fixed - Start now if 1, start when a problem is detected if 0
        trigger - Optional ID of event to start downtime from. Leave as 0 for
          fixed downtime.

        Syntax: [submitted] COMMAND;<host_name>;[<service_description>]
        <start_time>;<end_time>;<fixed>;<trigger_id>;<duration>;<author>;
        <comment>
        """

        entry_time = self._now()
        if start is None:
            start = entry_time

        hdr = "[%s] %s;%s;" % (entry_time, cmd, host)
        duration_s = (duration * 60)
        end = start + duration_s

        if not author:
            author = self.author

        if svc is not None:
            dt_args = [svc, str(start), str(end), str(fixed), str(trigger),
                       str(duration_s), author, comment]
        else:
            # Downtime for a host if no svc specified
            dt_args = [str(start), str(end), str(fixed), str(trigger),
                       str(duration_s), author, comment]

        dt_arg_str = ";".join(dt_args)
        dt_str = hdr + dt_arg_str + "\n"

        return dt_str

342
    def _fmt_notif_str(self, cmd, host=None, svc=None):
343 344 345 346
        """
        Format an external-command notification string.

        cmd - Nagios command ID.
347 348
        host - Host to en/disable notifications on.. A value is not required
          for global downtime
349 350 351 352 353 354 355
        svc - Service to schedule downtime for. A value is not required
          for host downtime.

        Syntax: [submitted] COMMAND;<host_name>[;<service_description>]
        """

        entry_time = self._now()
356 357 358 359 360
        notif_str = "[%s] %s" % (entry_time, cmd)
        if host is not None:
            notif_str += ";%s" % host
            
            if svc is not None:
361
                notif_str += ";%s" % svc
362 363

        notif_str += "\n"
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

        return notif_str

    def schedule_svc_downtime(self, host, services=[], minutes=30):
        """
        This command is used to schedule downtime for a particular
        service.

        During the specified downtime, Nagios will not send
        notifications out about the service.

        Syntax: SCHEDULE_SVC_DOWNTIME;<host_name>;<service_description>
        <start_time>;<end_time>;<fixed>;<trigger_id>;<duration>;<author>;
        <comment>
        """

        cmd = "SCHEDULE_SVC_DOWNTIME"
        for service in services:
            dt_cmd_str = self._fmt_dt_str(cmd, host, minutes, svc=service)
383
            self._write_command(dt_cmd_str)
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398

    def schedule_host_downtime(self, host, minutes=30):
        """
        This command is used to schedule downtime for a particular
        host.

        During the specified downtime, Nagios will not send
        notifications out about the host.

        Syntax: SCHEDULE_HOST_DOWNTIME;<host_name>;<start_time>;<end_time>;
        <fixed>;<trigger_id>;<duration>;<author>;<comment>
        """

        cmd = "SCHEDULE_HOST_DOWNTIME"
        dt_cmd_str = self._fmt_dt_str(cmd, host, minutes)
399
        self._write_command(dt_cmd_str)
400

401 402
    def schedule_host_svc_downtime(self, host, minutes=30):
        """
403
        This command is used to schedule downtime for
404
        all services associated with a particular host.
405 406 407 408

        During the specified downtime, Nagios will not send
        notifications out about the host.

409 410
        SCHEDULE_HOST_SVC_DOWNTIME;<host_name>;<start_time>;<end_time>;
        <fixed>;<trigger_id>;<duration>;<author>;<comment>
411 412 413 414 415 416
        """

        cmd = "SCHEDULE_HOST_SVC_DOWNTIME"
        dt_cmd_str = self._fmt_dt_str(cmd, host, minutes)
        self._write_command(dt_cmd_str)

417 418 419 420 421 422 423 424 425 426 427 428 429 430
    def schedule_hostgroup_host_downtime(self, hostgroup, minutes=30):
        """
        This command is used to schedule downtime for all hosts in a
        particular hostgroup.

        During the specified downtime, Nagios will not send
        notifications out about the hosts.

        Syntax: SCHEDULE_HOSTGROUP_HOST_DOWNTIME;<hostgroup_name>;<start_time>;
        <end_time>;<fixed>;<trigger_id>;<duration>;<author>;<comment>
        """

        cmd = "SCHEDULE_HOSTGROUP_HOST_DOWNTIME"
        dt_cmd_str = self._fmt_dt_str(cmd, hostgroup, minutes)
431
        self._write_command(dt_cmd_str)
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

    def schedule_hostgroup_svc_downtime(self, hostgroup, minutes=30):
        """
        This command is used to schedule downtime for all services in
        a particular hostgroup.

        During the specified downtime, Nagios will not send
        notifications out about the services.

        Note that scheduling downtime for services does not
        automatically schedule downtime for the hosts those services
        are associated with.

        Syntax: SCHEDULE_HOSTGROUP_SVC_DOWNTIME;<hostgroup_name>;<start_time>;
        <end_time>;<fixed>;<trigger_id>;<duration>;<author>;<comment>
        """

        cmd = "SCHEDULE_HOSTGROUP_SVC_DOWNTIME"
        dt_cmd_str = self._fmt_dt_str(cmd, hostgroup, minutes)
451
        self._write_command(dt_cmd_str)
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467

    def schedule_servicegroup_host_downtime(self, servicegroup, minutes=30):
        """
        This command is used to schedule downtime for all hosts in a
        particular servicegroup.

        During the specified downtime, Nagios will not send
        notifications out about the hosts.

        Syntax: SCHEDULE_SERVICEGROUP_HOST_DOWNTIME;<servicegroup_name>;
        <start_time>;<end_time>;<fixed>;<trigger_id>;<duration>;<author>;
        <comment>
        """

        cmd = "SCHEDULE_SERVICEGROUP_HOST_DOWNTIME"
        dt_cmd_str = self._fmt_dt_str(cmd, servicegroup, minutes)
468
        self._write_command(dt_cmd_str)
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488

    def schedule_servicegroup_svc_downtime(self, servicegroup, minutes=30):
        """
        This command is used to schedule downtime for all services in
        a particular servicegroup.

        During the specified downtime, Nagios will not send
        notifications out about the services.

        Note that scheduling downtime for services does not
        automatically schedule downtime for the hosts those services
        are associated with.

        Syntax: SCHEDULE_SERVICEGROUP_SVC_DOWNTIME;<servicegroup_name>;
        <start_time>;<end_time>;<fixed>;<trigger_id>;<duration>;<author>;
        <comment>
        """

        cmd = "SCHEDULE_SERVICEGROUP_SVC_DOWNTIME"
        dt_cmd_str = self._fmt_dt_str(cmd, servicegroup, minutes)
489
        self._write_command(dt_cmd_str)
490 491 492 493 494 495 496 497 498 499 500 501 502 503

    def disable_host_svc_notifications(self, host):
        """
        This command is used to prevent notifications from being sent
        out for all services on the specified host.

        Note that this command does not disable notifications from
        being sent out about the host.

        Syntax: DISABLE_HOST_SVC_NOTIFICATIONS;<host_name>
        """

        cmd = "DISABLE_HOST_SVC_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, host)
504
        self._write_command(notif_str)
505 506 507 508 509 510 511 512 513 514 515 516 517 518

    def disable_host_notifications(self, host):
        """
        This command is used to prevent notifications from being sent
        out for the specified host.

        Note that this command does not disable notifications for
        services associated with this host.

        Syntax: DISABLE_HOST_NOTIFICATIONS;<host_name>
        """

        cmd = "DISABLE_HOST_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, host)
519
        self._write_command(notif_str)
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534

    def disable_svc_notifications(self, host, services=[]):
        """
        This command is used to prevent notifications from being sent
        out for the specified service.

        Note that this command does not disable notifications from
        being sent out about the host.

        Syntax: DISABLE_SVC_NOTIFICATIONS;<host_name>;<service_description>
        """

        cmd = "DISABLE_SVC_NOTIFICATIONS"
        for service in services:
            notif_str = self._fmt_notif_str(cmd, host, svc=service)
535
            self._write_command(notif_str)
536 537 538 539 540 541 542 543 544 545 546 547 548 549

    def disable_servicegroup_host_notifications(self, servicegroup):
        """
        This command is used to prevent notifications from being sent
        out for all hosts in the specified servicegroup.

        Note that this command does not disable notifications for
        services associated with hosts in this service group.

        Syntax: DISABLE_SERVICEGROUP_HOST_NOTIFICATIONS;<servicegroup_name>
        """

        cmd = "DISABLE_SERVICEGROUP_HOST_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, servicegroup)
550
        self._write_command(notif_str)
551 552 553 554 555 556 557 558 559 560 561 562 563 564

    def disable_servicegroup_svc_notifications(self, servicegroup):
        """
        This command is used to prevent notifications from being sent
        out for all services in the specified servicegroup.

        Note that this does not prevent notifications from being sent
        out about the hosts in this servicegroup.

        Syntax: DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS;<servicegroup_name>
        """

        cmd = "DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, servicegroup)
565
        self._write_command(notif_str)
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580

    def disable_hostgroup_host_notifications(self, hostgroup):
        """
        Disables notifications for all hosts in a particular
        hostgroup.

        Note that this does not disable notifications for the services
        associated with the hosts in the hostgroup - see the
        DISABLE_HOSTGROUP_SVC_NOTIFICATIONS command for that.

        Syntax: DISABLE_HOSTGROUP_HOST_NOTIFICATIONS;<hostgroup_name>
        """

        cmd = "DISABLE_HOSTGROUP_HOST_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, hostgroup)
581
        self._write_command(notif_str)
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596

    def disable_hostgroup_svc_notifications(self, hostgroup):
        """
        Disables notifications for all services associated with hosts
        in a particular hostgroup.

        Note that this does not disable notifications for the hosts in
        the hostgroup - see the DISABLE_HOSTGROUP_HOST_NOTIFICATIONS
        command for that.

        Syntax: DISABLE_HOSTGROUP_SVC_NOTIFICATIONS;<hostgroup_name>
        """

        cmd = "DISABLE_HOSTGROUP_SVC_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, hostgroup)
597
        self._write_command(notif_str)
598 599 600 601 602 603 604 605 606 607 608 609 610

    def enable_host_notifications(self, host):
        """
        Enables notifications for a particular host.

        Note that this command does not enable notifications for
        services associated with this host.

        Syntax: ENABLE_HOST_NOTIFICATIONS;<host_name>
        """

        cmd = "ENABLE_HOST_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, host)
611
        self._write_command(notif_str)
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

    def enable_host_svc_notifications(self, host):
        """
        Enables notifications for all services on the specified host.

        Note that this does not enable notifications for the host.

        Syntax: ENABLE_HOST_SVC_NOTIFICATIONS;<host_name>
        """

        cmd = "ENABLE_HOST_SVC_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, host)
        nagios_return = self._write_command(notif_str)

        if nagios_return:
            return notif_str
        else:
            return "Fail: could not write to the command file"

    def enable_svc_notifications(self, host, services=[]):
        """
        Enables notifications for a particular service.

        Note that this does not enable notifications for the host.

        Syntax: ENABLE_SVC_NOTIFICATIONS;<host_name>;<service_description>
        """

        cmd = "ENABLE_SVC_NOTIFICATIONS"
        nagios_return = True
        return_str_list = []
        for service in services:
            notif_str = self._fmt_notif_str(cmd, host, svc=service)
645
            nagios_return = self._write_command(notif_str) and nagios_return
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
            return_str_list.append(notif_str)

        if nagios_return:
            return return_str_list
        else:
            return "Fail: could not write to the command file"

    def enable_hostgroup_host_notifications(self, hostgroup):
        """
        Enables notifications for all hosts in a particular hostgroup.

        Note that this command does not enable notifications for
        services associated with the hosts in this hostgroup.

        Syntax: ENABLE_HOSTGROUP_HOST_NOTIFICATIONS;<hostgroup_name>
        """

        cmd = "ENABLE_HOSTGROUP_HOST_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, hostgroup)
        nagios_return = self._write_command(notif_str)

        if nagios_return:
            return notif_str
        else:
            return "Fail: could not write to the command file"

    def enable_hostgroup_svc_notifications(self, hostgroup):
        """
        Enables notifications for all services that are associated
        with hosts in a particular hostgroup.

        Note that this does not enable notifications for the hosts in
        this hostgroup.

        Syntax: ENABLE_HOSTGROUP_SVC_NOTIFICATIONS;<hostgroup_name>
        """

        cmd = "ENABLE_HOSTGROUP_SVC_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, hostgroup)
        nagios_return = self._write_command(notif_str)

        if nagios_return:
            return notif_str
        else:
            return "Fail: could not write to the command file"

    def enable_servicegroup_host_notifications(self, servicegroup):
        """
        Enables notifications for all hosts that have services that
        are members of a particular servicegroup.

        Note that this command does not enable notifications for
        services associated with the hosts in this servicegroup.

        Syntax: ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS;<servicegroup_name>
        """

        cmd = "ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, servicegroup)
        nagios_return = self._write_command(notif_str)

        if nagios_return:
            return notif_str
        else:
            return "Fail: could not write to the command file"

    def enable_servicegroup_svc_notifications(self, servicegroup):
        """
        Enables notifications for all services that are members of a
        particular servicegroup.

        Note that this does not enable notifications for the hosts in
        this servicegroup.

        Syntax: ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS;<servicegroup_name>
        """

        cmd = "ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS"
        notif_str = self._fmt_notif_str(cmd, servicegroup)
        nagios_return = self._write_command(notif_str)

        if nagios_return:
            return notif_str
        else:
            return "Fail: could not write to the command file"

    def silence_host(self, host):
        """
        This command is used to prevent notifications from being sent
        out for the host and all services on the specified host.

        This is equivalent to calling disable_host_svc_notifications
        and disable_host_notifications.

        Syntax: DISABLE_HOST_SVC_NOTIFICATIONS;<host_name>
        Syntax: DISABLE_HOST_NOTIFICATIONS;<host_name>
        """

        cmd = [
            "DISABLE_HOST_SVC_NOTIFICATIONS",
            "DISABLE_HOST_NOTIFICATIONS"
            ]
        nagios_return = True
        return_str_list = []
        for c in cmd:
            notif_str = self._fmt_notif_str(c, host)
752
            nagios_return = self._write_command(notif_str) and nagios_return
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
            return_str_list.append(notif_str)

        if nagios_return:
            return return_str_list
        else:
            return "Fail: could not write to the command file"

    def unsilence_host(self, host):
        """
        This command is used to enable notifications for the host and
        all services on the specified host.

        This is equivalent to calling enable_host_svc_notifications
        and enable_host_notifications.

        Syntax: ENABLE_HOST_SVC_NOTIFICATIONS;<host_name>
        Syntax: ENABLE_HOST_NOTIFICATIONS;<host_name>
        """

        cmd = [
            "ENABLE_HOST_SVC_NOTIFICATIONS",
            "ENABLE_HOST_NOTIFICATIONS"
            ]
        nagios_return = True
        return_str_list = []
        for c in cmd:
            notif_str = self._fmt_notif_str(c, host)
780
            nagios_return = self._write_command(notif_str) and nagios_return
781 782 783 784 785 786
            return_str_list.append(notif_str)

        if nagios_return:
            return return_str_list
        else:
            return "Fail: could not write to the command file"
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    
    def silence_nagios(self):
        """
        This command is used to disable notifications for all hosts and services
        in nagios.
        
        This is a 'SHUT UP, NAGIOS' command
        """
        cmd = 'DISABLE_NOTIFICATIONS'
        self._write_command(self._fmt_notif_str(cmd))
    
    def unsilence_nagios(self):
        """
        This command is used to enable notifications for all hosts and services
        in nagios.
        
        This is a 'OK, NAGIOS, GO'' command
        """
        cmd = 'ENABLE_NOTIFICATIONS'
        self._write_command(self._fmt_notif_str(cmd))
        
    def nagios_cmd(self, cmd):
        """
        This sends an arbitrary command to nagios
        
        It prepends the submitted time and appends a \n
        
        You just have to provide the properly formatted command
        """
        
        pre = '[%s]' % int(time.time())
        
        post = '\n'
        cmdstr = '%s %s %s' % (pre, cmd, post)
        self._write_command(cmdstr)
        
823 824 825 826 827 828 829 830 831
    def act(self):
        """
        Figure out what you want to do from ansible, and then do the
        needful (at the earliest).
        """
        # host or service downtime?
        if self.action == 'downtime':
            if self.services == 'host':
                self.schedule_host_downtime(self.host, self.minutes)
832 833
            elif self.services == 'all':
                self.schedule_host_svc_downtime(self.host, self.minutes)
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
            else:
                self.schedule_svc_downtime(self.host,
                                           services=self.services,
                                           minutes=self.minutes)

        # toggle the host AND service alerts
        elif self.action == 'silence':
            self.silence_host(self.host)

        elif self.action == 'unsilence':
            self.unsilence_host(self.host)

        # toggle host/svc alerts
        elif self.action == 'enable_alerts':
            if self.services == 'host':
                self.enable_host_notifications(self.host)
            else:
                self.enable_svc_notifications(self.host,
                                              services=self.services)

        elif self.action == 'disable_alerts':
            if self.services == 'host':
                self.disable_host_notifications(self.host)
            else:
                self.disable_svc_notifications(self.host,
                                               services=self.services)
860 861 862 863 864 865 866 867 868
        elif self.action == 'silence_nagios':
            self.silence_nagios()
            
        elif self.action == 'unsilence_nagios':
            self.unsilence_nagios()
            
        elif self.action == 'command':
            self.nagios_cmd(self.command)
            
869 870 871 872 873 874 875 876 877
        # wtf?
        else:
            self.module.fail_json(msg="unknown action specified: '%s'" % \
                                      self.action)

        self.module.exit_json(nagios_commands=self.command_results,
                              changed=True)

######################################################################
878
# import module snippets
879
from ansible.module_utils.basic import *
880
main()