File: __init__.py

package info (click to toggle)
pynag 1.1.2+dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 1,324 kB
  • sloc: python: 9,792; makefile: 200
file content (1077 lines) | stat: -rw-r--r-- 40,144 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
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
645
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
752
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
780
781
782
783
784
785
786
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
823
824
825
826
827
828
829
830
831
832
833
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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
# -*- coding: utf-8 -*-
#
# pynag - Python Nagios plug-in and configuration environment
# Copyright (C) 2010 Drew Stinnet
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""
Python Nagios extensions
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

import sys
import os
import traceback
import signal
from optparse import OptionParser, OptionGroup
from pynag.Utils import PerfData, reconsile_threshold
from pynag.Parsers import ExtraOptsParser
import pynag.Utils
import pynag.errors
from pynag.Plugins import new_threshold_syntax
from pynag.Plugins import classic_threshold_syntax
import six

# The following constants, and state, state_text below are considered deprecated.
# Use pynag.Utils.states module instead.
OK, WARNING, CRITICAL, UNKNOWN = 0, 1, 2, 3
ok, warning, critical, unknown = 0, 1, 2, 3

state = {}
state['ok'] = 0
state['warning'] = 1
state['warn'] = 1
state['w'] = 1
state['critical'] = 2
state['crit'] = 2
state['c'] = 2
state['unknown'] = 3
state['u'] = 3
state['UP'] = 0
state['DOWN'] = 2
state['UNREACHABLE'] = 2
state['OK'] = 0
state['WARNING'] = 1
state['CRITICAL'] = 2
state['UNKNOWN'] = 3

state_text = {}
state_text[ok] = 'OK'
state_text[warning] = 'Warning'
state_text[critical] = "Critical"
state_text[unknown] = "Unknown"


class PluginError(pynag.errors.PynagError):
    """Base class for errors in this module."""


class simple(object):

    """
    Nagios plugin helper library based on Nagios::Plugin

    Sample usage

    from pynag.Plugins import WARNING, CRITICAL, OK, UNKNOWN, simple as Plugin

    # Create plugin object
    np = Plugin()
    # Add arguments
    np.add_arg("d", "disk")
    # Do activate plugin
    np.activate()
    ... check stuff, np['disk'] to address variable assigned above...
    # Add a status message and severity
    np.add_message( WARNING, "Disk nearing capacity" )
    # Get parsed code and messages
    (code, message) = np.check_messages()
    # Return information and exit
    nagios_exit(code, message)
    """

    def __init__(self, shortname=None, version=None, blurb=None, extra=None, url=None, license=None, plugin=None, timeout=15, must_threshold=True):

        # this is the custom parser
        self.extra_list_optional = []
        self.extra_list_required = []

        # Set the option parser stuff here
        self.parser = OptionParser()

        # Variables we'll get later
        self.opts = None
        self.must_threshold = must_threshold
        self.data = {}
        self.data['perfdata'] = []
        self.data['messages'] = {
            OK: [], WARNING: [], CRITICAL: [], UNKNOWN: []}
        self.data['threshhold'] = None

        # Error mappings, for easy access
        self.errors = {"OK": 0, "WARNING": 1, "CRITICAL": 2, "UNKNOWN": 3, }
        self.status_text = {
            0: "OK", 1: "WARNING", 2: "CRITICAL", 3: "UNKNOWN", }

        # Shortname creation
        if not shortname:
            self.data['shortname'] = os.path.basename("%s" % sys.argv[0])
        else:
            self.data['shortname'] = shortname

    def add_arg(self, spec_abbr, spec, help_text, required=1, action="store"):
        """
        Add an argument to be handled by the option parser.  By default, the arg is not required.

        required = optional parameter
        action = [store, append, store_true]
        """
        self.parser.add_option("-%s" % spec_abbr, "--%s" % spec, dest="%s" %
                               spec, help=help_text, metavar="%s" % spec.upper(), action=action)
        if required:
            self.extra_list_required.append(spec)
        else:
            self.extra_list_optional.append(spec)

    def activate(self):
        """
        Parse out all command line options and get ready to process the plugin.  This should be run after argument preps
        """
        timeout = None
        verbose = 0

        self.parser.add_option(
            "-v", "--verbose", dest="verbose", help="Verbosity Level", metavar="VERBOSE", default=0)
        self.parser.add_option(
            "-H", "--host", dest="host", help="Target Host", metavar="HOST")
        self.parser.add_option(
            "-t", "--timeout", dest="timeout", help="Connection Timeout", metavar="TIMEOUT")

        if self.must_threshold is True:
            self.parser.add_option(
                "-c", "--critical", dest="critical", help="Critical Threshhold", metavar="CRITICAL")
            self.parser.add_option(
                "-w", "--warning", dest="warning", help="Warn Threshhold", metavar="WARNING")

        (options, args) = self.parser.parse_args()

        # Set verbosity level
        if int(options.verbose) in (0, 1, 2, 3):
            self.data['verbosity'] = int(options.verbose)
        else:
            self.data['verbosity'] = verbose

        # Ensure the hostname is set
        if options.host:
            self.data['host'] = options.host

        # Set timeout
        if options.timeout:
            self.data['timeout'] = options.timeout
        else:
            self.data['timeout'] = timeout

        if self.must_threshold is True and not options.critical and not options.warning:
            self.parser.error(
                "You must provide a WARNING and/or CRITICAL value")

        # Set Critical; if the option is available in the plugin
        if hasattr(options, 'critical'):
            self.data['critical'] = options.critical
        else:
            self.data['critical'] = None

        # Set Warn; if the option is available in the plugin
        if hasattr(options, 'warning'):
            self.data['warning'] = options.warning
        else:
            self.data['warning'] = None

        # Ensurethat the extra items are provided
        for extra_item in self.extra_list_required:
            if not options.__dict__[extra_item]:
                self.parser.error("option '%s' is required" % extra_item)

        # Put the remaining values into the data dictionary
        for key, value in options.__dict__.items():
            if key in (self.extra_list_required + self.extra_list_optional):
                self.data[key] = value

    def add_perfdata(self, label, value, uom=None, warn=None, crit=None, minimum=None, maximum=None):
        """
        Append perfdata string to the end of the message
        """

        # Append perfdata (assume multiple)
        self.data[
            'perfdata'].append({'label': label, 'value': value, 'uom': uom,
                                'warn': warn, 'crit': crit, 'min': minimum, 'max': maximum})

    def check_perfdata_as_metric(self):
        for perfdata in self.data['perfdata']:
            self._add_message_from_range_check(
                perfdata['value'],
                perfdata['warn'],
                perfdata['crit'],
                perfdata['label']
            )

        self._check_messages_and_exit()

    def _add_message_from_range_check(self, value, warning=None, critical=None, label='data'):
        if not (critical or warning):
            critical = self.data['critical']
            warning = self.data['warning']

        if critical and not self._range_checker(value, critical):
            self.add_message(CRITICAL, "%s %s is outside critical range: %s" %
                             (label, value, critical))
        elif warning and not self._range_checker(value, warning):
            self.add_message(
                WARNING, "%s %s is outside warning range: %s" % (label, value, warning))
        else:
            self.add_message(OK, "%s %s is inside warning=%s and critical=%s" %
                             (label, value, warning, critical))

    def _check_messages_and_exit(self):
        # Get all messages appended and exit code
        (code, message) = self.check_messages()

        # Exit with appropriate exit status and message
        self.nagios_exit(code, message)

    def check_range(self, value):
        """
        Check if a value is within a given range.  This should replace change_threshold eventually. Exits with appropriate exit code given the range.

        Taken from:  http://nagiosplug.sourceforge.net/developer-guidelines.html
        Range definition

        Generate an alert if x...
        10        < 0 or > 10, (outside the range of {0 .. 10})
        10:        < 10, (outside {10 .. #})
        ~:10    > 10, (outside the range of {-# .. 10})
        10:20    < 10 or > 20, (outside the range of {10 .. 20})
        @10:20    # 10 and # 20, (inside the range of {10 .. 20})
        """
        self.hr_range = ""

        self._add_message_from_range_check(value)
        self._check_messages_and_exit()

    def _range_checker(self, value, range_threshold):
        """ deprecated. Use pynag.Plugins.classic_threshold_syntax.check_range() """
        return check_range(value=value, range_threshold=range_threshold)

    def send_nsca(self, *args, **kwargs):
        """ Wrapper around pynag.Utils.send_nsca - here for backwards compatibility """

        # Previous versions of this method had a typo where one argument was called
        # ncsahost instead of nscahost. We will maintain backwards compatibility here.
        if 'ncsahost' in kwargs and not 'nscahost' in kwargs:
            kwargs['nscahost'] = kwargs['ncsahost']
            del kwargs['ncsahost']
        pynag.Utils.send_nsca(*args, **kwargs)
        return 0

    def nagios_exit(self, code_text, message):
        """
        Exit with exit_code, message, and optionally perfdata
        """

        # Change text based codes to int
        code = self.code_string2int(code_text)

        # This should be one line (or more in nagios 3)
        print("%s: %s %s" % (self.status_text[code], message, self.perfdata_string()))
        sys.exit(code)

    def perfdata_string(self):

        # Append perfdata to the message, if perfdata exists
        if self.data['perfdata']:
            append = '|'
        else:
            append = ''

        for pd in self.data['perfdata']:
            append += " '%s'=%s%s;%s;%s;%s;%s" % (
                pd['label'],
                pd['value'],
                pd['uom'] or '',
                pd['warn'] or '',
                pd['crit'] or '',
                pd['min'] or '',
                pd['max'] or '')

        return append

    def add_message(self, code, message):
        """
        Add a message with code to the object. May be called
        multiple times.  The messages added are checked by check_messages,
        following.

        Only CRITICAL, WARNING, OK and UNKNOWN are accepted as valid codes.
        """
        # Change text based codes to int
        code = self.code_string2int(code)

        self.data['messages'][code].append(message)

    def check_messages(self, joinstr=" ", joinallstr=None):
        """
        Check the current set of messages and return an appropriate nagios
        return code and/or a result message. In scalar context, returns
        only a return code; in list context returns both a return code and
        an output message, suitable for passing directly to nagios_exit()

        joinstr = string
            A string used to join the relevant array to generate the
            message string returned in list context i.e. if the 'critical'
            array is non-empty, check_messages would return:
                joinstr.join(critical)

        joinallstr = string
            By default, only one set of messages are joined and returned in
            the result message i.e. if the result is CRITICAL, only the
            'critical' messages are included in the result; if WARNING,
            only the 'warning' messages are included; if OK, the 'ok'
            messages are included (if supplied) i.e. the default is to
            return an 'errors-only' type message.

            If joinallstr is supplied, however, it will be used as a string
            to join the resultant critical, warning, and ok messages
            together i.e.  all messages are joined and returned.
        """
        # Check for messages in unknown, critical, warning, ok to determine
        # code
        keys = list(self.data['messages'].keys())
        keys.sort(reverse=True)
        code = UNKNOWN
        for code in keys:
            if len(self.data['messages'][code]):
                break

        # Create the relevant message for the most severe code
        if joinallstr is None:
            message = joinstr.join(self.data['messages'][code])
        # Join all strings whether OK, WARN...
        else:
            message = ""
            for c in keys:
                if len(self.data['messages'][c]):
                    message += joinallstr.join(
                        self.data['messages'][c]) + joinallstr

        return code, message.rstrip(joinallstr)

    def code_string2int(self, code_text):
        """
        Changes CRITICAL, WARNING, OK and UNKNOWN code_text to integer
        representation for use within add_message() and nagios_exit()
        """

        # If code_text is a string, convert to the int
        try:
            code = self.errors[str(code_text)]
        except KeyError:
            code = code_text

        return code

    def __setitem__(self, key, item):
        self.data[key] = item

    def __getitem__(self, key):
        if key in self.data:
            return self.data[key]
        else:
            return None


class PluginHelper(object):

    """ PluginHelper takes away some of the tedious work of writing Nagios plugins. Primary features include:

    * Keep a collection of your plugin messages (queue for both summary and longoutput)
    * Keep record of exit status
    * Keep a collection of your metrics (for both perfdata and thresholds)
    * Automatic Command-line arguments
    * Make sure output of your plugin is within Plugin Developer Guidelines

    Usage:
    p = PluginHelper()
    p.status(warning)
    p.add_summary('Example Plugin with warning status')
    p.add_metric('cpu load', '90')
    p.exit()
    """
    _nagios_status = -1     # exit status of the plugin
    _long_output = None     # Long output of the plugin
    _summary = None         # Summary of the plugin
    _perfdata = None        # Performance and Threshold Metrics are stored here
    show_longoutput = True  # If True, print longoutput
    show_perfdata = True    # If True, print perfdata
    show_summary = True     # If True, print Summary
    show_status_in_summary = True
    show_legacy = False     # Deprecated, doesnt do anything
    verbose = False         # Extra verbosity
    show_debug = False      # Extra debugging
    # By default, plugins timeout right before nagios kills the plugin
    timeout = 58

    thresholds = None       # List of strings in the nagios threshold format
    options = None          # OptionParser() options
    arguments = None        # OptionParser() arguments

    def __init__(self):
        self._long_output = []
        self._summary = []
        self.thresholds = []
        # Performance and Threshold Metrics are stored here
        self._perfdata = PerfData()

        self.parser = OptionParser()
        generic_group = OptionGroup(self.parser, "Generic Options")
        generic_group.add_option(
            '--timeout',
            help="Exit plugin with unknown status after x seconds",
            type='int',
            metavar='50',
            dest="timeout",
            default=self.timeout
        )
        generic_group.add_option(
            '--threshold',
            default=[],
            help="Thresholds in standard nagios threshold format",
            metavar='range',
            dest="thresholds",
            action="append"
        )
        generic_group.add_option(
            '--th',
            default=[],
            help="Same as --threshold",
            metavar='range',
            dest="thresholds",
            action="append"
        )

        generic_group.add_option(
            '--extra-opts',
            help="Read options from an ini file. See http://nagiosplugins.org/extra-opts",
            metavar='@file',
            dest="extra_opts"
        )
        generic_group.add_option(
            "-d", "--debug",
            dest="show_debug",
            help="Print debug info",
            metavar="d",
            action="store_true",
            default=self.show_debug
        )

        # Display options are options that affect the output of the plugin
        # But usually not its function
        display_group = OptionGroup(self.parser, "Display Options")
        display_group.add_option(
            "-v", "--verbose",
            dest="verbose",
            help="Print more verbose info",
            metavar="v",
            action="store_true",
            default=self.verbose
        )
        display_group.add_option(
            "--no-perfdata",
            dest="show_perfdata",
            help="Dont show any performance data",
            action="store_false",
            default=self.show_perfdata
        )
        display_group.add_option(
            "--no-longoutput",
            dest="show_longoutput",
            help="Hide longoutput from the plugin output (i.e. only display first line of the output)",
            action="store_false",
            default=self.show_longoutput
        )
        display_group.add_option(
            "--no-summary",
            dest="show_summary",
            help="Hide summary from plugin output",
            action="store_false",
            default=self.show_summary
        )

        display_group.add_option(
            "--get-metrics",
            dest="get_metrics",
            help="Print all available metrics and exit (can be combined with --verbose)",
            action="store_true",
            default=False
        )
        display_group.add_option(
            "--legacy",
            dest="show_legacy",
            help="Deprecated, do not use",
            action="store_true",
            default=self.show_legacy
        )

        self.parser.add_option_group(generic_group)
        self.parser.add_option_group(display_group)

    def parse_arguments(self, argument_list=None):
        """ Parsers commandline arguments, prints error if there is a syntax error.

        Creates:
            self.options   -- As created by OptionParser.parse()
            self.arguments -- As created by OptionParser.parse()
        Arguments:
            argument_list -- By default use sys.argv[1:], override only if you know what you are doing.
        Returns:
            None
        """
        self.options, self.arguments = self.parser.parse_args(
            args=argument_list)

        extra_opts = self.options.extra_opts
        if extra_opts is not None:  # --extra-opts was specified
            if extra_opts == '':  # --extra-opts= with no value.
                section_name = None
                config_file = None
            elif '@' in extra_opts:  # filename was specified
                section_name, config_file = extra_opts.split('@', 1)
            else:  # Only section was specified
                section_name = extra_opts
                config_file = None
            values = self.get_default_values(section_name, config_file)
            self.options, self.arguments = self.parser.parse_args(
                args=argument_list, values=values)

        # TODO: Handle it if developer decides to remove some options before
        # calling parse_arguments()
        self.thresholds = self.options.thresholds
        self.show_longoutput = self.options.show_longoutput
        self.show_perfdata = self.options.show_perfdata
        self.show_legacy = self.options.show_legacy
        self.show_debug = self.options.show_debug
        self.verbose = self.options.verbose
        #self.show_status_in_summary = self.options.show_status_in_summary

        self.set_timeout(self.options.timeout)

    def add_long_output(self, message):
        """ Appends message to the end of Plugin long_output. Message does not need a \n suffix

        Examples:
          >>> p = PluginHelper()
          >>> p.add_long_output('Status of sensor 1')
          >>> p.add_long_output('* Temperature: OK')
          >>> p.add_long_output('* Humidity: OK')
          >>> p.get_long_output() == six.u(str('Status of sensor 1\\n* Temperature: OK\\n* Humidity: OK'))
          True
        """
        self._long_output.append(message)

    def add_option(self, *args, **kwargs):
        """ Same as self.parser.add_option() """
        return self.parser.add_option(*args, **kwargs)

    def get_long_output(self):
        """ Returns all long_output that has been added via add_long_output """
        return '\n'.join(self._long_output)

    def set_long_output(self, message):
        """ Overwrite current long_output with message

        Example:
        >>> s = PluginHelper()
        >>> s.add_long_output('first long output')
        >>> s.set_long_output('Fatal error')
        >>> s.get_long_output() == six.u(str('Fatal error'))
        True
        """
        self._long_output = [message]

    def add_summary(self, message):
        """ Adds message to Plugin Summary """
        self._summary.append(message.strip())

    def set_summary(self, message):
        """ Overwrite current summary with message

        Example:
        >>> s = PluginHelper()
        >>> s.add_summary('first summary')
        >>> s.set_summary('Fatal error')
        >>> s.get_summary() == six.u(str('Fatal error'))
        True
        """
        self._summary = [message]

    def get_summary(self):
        return '. '.join(self._summary)

    def get_status(self):
        """ Returns the worst nagios status (integer 0,1,2,3) that has been put with add_status()

        If status has never been added, returns 3 for UNKNOWN
        """

        # If no status has been set, return unknown
        if self._nagios_status == -1:
            return UNKNOWN
        else:
            return self._nagios_status

    def status(self, new_status=None):
        """ Same as get_status() if new_status=None, otherwise call add_status(new_status) """
        if new_status is None:
            return self.get_status()
        if new_status not in state_text:
            new_status = unknown
        return self.add_status(new_status)

    def add_status(self, new_status=None):
        """ Update exit status of the nagios plugin. This function will keep history of the worst status added

        Examples:
        >>> p = PluginHelper()
        >>> p.add_status(0) # ok
        >>> p.add_status(2) # critical
        >>> p.add_status(1) # warning
        >>> p.get_status()  #
        2

        >>> p = PluginHelper()
        >>> p.add_status('warning')
        >>> p.add_status('ok')
        >>> p.get_status()
        1
        >>> p.add_status('okay')
        Traceback (most recent call last):
        ...
        Exception: Invalid status supplied "okay"
        """

        # If new status was entered as a human readable string (ok,warn,etc)
        # lets convert it to int:
        if isinstance(new_status, six.string_types):
            if new_status.lower() in state:
                new_status = state[new_status]
            else:
                raise Exception(
                    "Invalid status supplied \"%s\"" % (new_status))

        self._nagios_status = max(self._nagios_status, new_status)

    def add_metric(self, label="", value="", warn="", crit="", min="", max="", uom="", perfdatastring=None):
        """ Add numerical metric (will be outputted as nagios performanca data)

        Examples:
          >>> p = PluginHelper()
          >>> p.add_metric(label="load1", value="7")
          >>> p.add_metric(label="load5", value="5")
          >>> p.add_metric(label="load15",value="2")
          >>> p.get_perfdata()
          "'load1'=7;;;; 'load5'=5;;;; 'load15'=2;;;;"

          >>> p = PluginHelper()
          >>> p.add_metric(perfdatastring="load1=6;;;;")
          >>> p.add_metric(perfdatastring="load5=4;;;;")
          >>> p.add_metric(perfdatastring="load15=1;;;;")
          >>> p.get_perfdata()
          "'load1'=6;;;; 'load5'=4;;;; 'load15'=1;;;;"

        """
        if not perfdatastring is None:
            self._perfdata.add_perfdatametric(perfdatastring=perfdatastring)
        else:
            self._perfdata.add_perfdatametric(
                label=label, value=value, warn=warn, crit=crit, min=min, max=max, uom=uom)

    def get_default_values(self, section_name=None, config_file=None):
        """ Returns an optionParser.Values instance of all defaults after parsing extra opts config file

        The Nagios extra-opts spec we use is the same as described here: http://nagiosplugins.org/extra-opts

        Arguments

        """
        # Get the program defaults
        values = self.parser.get_default_values()

        # Create an ExtraOptsParser instance and get all the values from that
        # config file
        extra_opts = ExtraOptsParser(
            section_name=section_name, config_file=config_file).get_values()

        for option in self.parser.option_list:
            name = option.dest
            if name in extra_opts:
                if option.action == 'append':
                    setattr(values, name, extra_opts[option.dest])
                else:
                    setattr(values, name, extra_opts[option.dest][0])
        return values

    def get_metric(self, label):
        """ Return one specific metric (PerfdataMetric object) with the specified label. Returns None if not found.

        Example:
        >>> p = PluginHelper()
        >>> p.add_metric(label="load1", value="7")
        >>> p.add_metric(label="load15",value="2")
        >>> p.get_metric("load1")
        'load1'=7;;;;
        >>> p.get_metric("unknown") # Returns None

        """
        for i in self._perfdata.metrics:
            if i.label == label:
                return i
        return None

    def convert_perfdata(self, perfdata):
        """ Converts new threshold range format to old one. Returns None.

        Examples:
            x..y -> x:y
            inf..y -> :y
            -inf..y -> :y
            x..inf -> x:
            -inf..inf -> :
        """
        for metric in perfdata:
            metric.warn = reconsile_threshold(metric.warn)
            metric.crit = reconsile_threshold(metric.crit)
        return None

    def get_perfdata(self):
        """ Get perfdatastring for all valid perfdatametrics collected via add_perfdata

        Examples:
        >>> p = PluginHelper()
        >>> p.add_metric(label="load1", value="7", warn="-inf..10", crit="10..inf")
        >>> p.add_metric(label="load5", value="5", warn="-inf..7", crit="7..inf")
        >>> p.add_metric(label="load15",value="2", warn="-inf..5", crit="5..inf")
        >>> p.get_perfdata()
        "'load1'=7;10:;~:10;; 'load5'=5;7:;~:7;; 'load15'=2;5:;~:5;;"

        Example with legacy output (show_legacy should be set with a cmdline option):
        >>> p.show_legacy = True
        >>> p.get_perfdata()
        "'load1'=7;10:;~:10;; 'load5'=5;7:;~:7;; 'load15'=2;5:;~:5;;"

        """
        # Normalize the perfdata to so the thresholds match the current nagios plugin guidelines
        self.convert_perfdata(self._perfdata.metrics)
        return str(self._perfdata)

    def get_plugin_output(self, exit_code=None, summary=None, long_output=None, perfdata=None):
        """ Get all plugin output as it would be printed to screen with self.exit()

        Examples of functionality:
        >>> p = PluginHelper()
        >>> p.get_plugin_output() == six.u(str('Unknown -'))
        True

        >>> p = PluginHelper()
        >>> p.add_summary('Testing')
        >>> p.add_long_output('Long testing output')
        >>> p.add_long_output('More output')
        >>> p.get_plugin_output(exit_code=0) == six.u(str('OK - Testing\\nLong testing output\\nMore output'))
        True

        >>> p = PluginHelper()
        >>> p.add_summary('Testing')
        >>> p.add_status(0)
        >>> p.get_plugin_output() == six.u(str('OK - Testing'))
        True

        >>> p = PluginHelper()
        >>> p.show_status_in_summary = False
        >>> p.add_summary('Testing')
        >>> p.add_metric(label="load1", value="7")
        >>> p.add_metric(label="load5", value="5")
        >>> p.add_metric(label="load15",value="2")
        >>> p.get_plugin_output(exit_code=0) == six.u(str("Testing | 'load1'=7;;;; 'load5'=5;;;; 'load15'=2;;;;"))
        True

        >>> p = PluginHelper()
        >>> p.show_status_in_summary = False
        >>> p.add_summary('Testing')
        >>> p.add_long_output('Long testing output')
        >>> p.add_long_output('More output')
        >>> p.add_metric(label="load1", value="7")
        >>> p.add_metric(label="load5", value="5")
        >>> p.add_metric(label="load15",value="2")
        >>> p.get_plugin_output(exit_code=0) == six.u(str("Testing | 'load1'=7;;;; 'load5'=5;;;; 'load15'=2;;;;\\nLong testing output\\nMore output"))
        True

        """
        if summary is None:
            summary = self.get_summary()
        if long_output is None:
            long_output = self.get_long_output()
        if perfdata is None:
            perfdata = self.get_perfdata()
        if exit_code is None:
            exit_code = self.get_status()

        return_buffer = ""
        if self.show_status_in_summary is True:
            return_buffer += "%s - " % state_text[exit_code]
        if self.show_summary is True:
            return_buffer += summary
        if self.show_perfdata is True and len(perfdata) > 0:
            return_buffer += " | %s\n" % perfdata

        if not return_buffer.endswith('\n'):
            return_buffer += '\n'
        if self.show_longoutput is True and len(long_output) > 0:
            return_buffer += long_output

        return_buffer = return_buffer.strip()
        return return_buffer

    def set_timeout(self, seconds=50):
        """ Configures plugin to timeout after seconds number of seconds """
        timeout = lambda x, y: self.exit(
            unknown, summary="Plugin timeout exceeded after %s seconds." % seconds)
        signal.signal(signal.SIGALRM, timeout)
        signal.alarm(seconds)

    def exit(self, exit_code=None, summary=None, long_output=None, perfdata=None):
        """ Print all collected output to screen and exit nagios style, no arguments are needed
            except if you want to override default behavior.

        Arguments:
            summary     -- Is this text as the plugin summary instead of self.get_summary()
            long_output -- Use this text as long_output instead of self.get_long_output()
            perfdata    -- Use this text instead of self.get_perfdata()
            exit_code   -- Use this exit code instead of self.status()
        """
        if exit_code is None:
            exit_code = self.get_status()
        if self.options and self.options.get_metrics is True:
            summary = "Available metrics for this plugin:"
            metrics = []

            for i in self._perfdata.metrics:
                if self.options.verbose is True:
                    metrics.append(str(i))
                else:
                    metrics.append(i.label)
            long_output = '\n'.join(metrics)

        plugin_output = self.get_plugin_output(
            exit_code=exit_code, summary=summary, long_output=long_output, perfdata=perfdata)

        print(plugin_output)
        sys.exit(exit_code)

    def check_metric(self, metric_name, thresholds):
        """ Check one specific metric against a list of thresholds. Updates self.status() and writes to summary or longout as appropriate.

        Arguments:
          metric_name -- A string representing the name of the metric (the label part of the performance data)
          thresholds  -- a list in the form of [ (level,range) ] where range is a string in the format of "start..end"

        Examples:
        >>> p = PluginHelper()
        >>> thresholds = [(warning,'2..5'), (critical,'5..inf')]
        >>> p.get_plugin_output() == six.u(str('Unknown -'))
        True
        >>> p.add_metric('load15', '3')
        >>> p.check_metric('load15',thresholds)
        >>> p.get_plugin_output() == six.u(str("Warning - Warning on load15 | 'load15'=3;@2:5;~:5;;"))
        True
        >>> p = PluginHelper()
        >>> thresholds = [(warning,'2..5'), (critical,'5..inf')]
        >>> p.add_metric('load15', '3')
        >>> p.verbose = True
        >>> p.check_metric('load15',thresholds)
        >>> p.get_plugin_output() == six.u(str("Warning - Warning on load15 | 'load15'=3;@2:5;~:5;;\\nWarning on load15"))
        True

        Invalid metric:
        >>> p = PluginHelper()
        >>> p.add_status(ok)
        >>> p.add_summary('Everythings fine!')
        >>> p.get_plugin_output() == six.u(str('OK - Everythings fine!'))
        True
        >>> thresholds = [(warning,'2..5'), (critical,'5..inf')]
        >>> p.check_metric('never_added_metric', thresholds)
        >>> p.get_plugin_output() == six.u(str('Unknown - Everythings fine!. Metric never_added_metric not found'))
        True

        Invalid threshold:
        >>> p = PluginHelper()
        >>> thresholds = [(warning, 'invalid'), (critical,'5..inf')]
        >>> p.add_metric('load1', '10')
        >>> p.check_metric('load1', thresholds)
        Traceback (most recent call last):
        ...
        SystemExit: 3

        Returns:
          None
        """
        metric = self.get_metric(label=metric_name)

        # If threshold was specified but metric not found in our data, set
        # status unknown
        if metric is None:
            self.status(unknown)
            self.add_summary("Metric %s not found" % (metric_name))
            return

        metric_status = -1  # by default assume nothing
        default_state = 0  # By default if no treshold matches, we assume OK
        highest_level = ok  # highest threshold range seen
        # Iterate through all thresholds, and log down warn and crit for
        # perfdata purposes
        for level, threshold_range in thresholds:
            if metric.warn == '' and level == warning:
                metric.warn = threshold_range
            elif metric.crit == '' and level == critical:
                metric.crit = threshold_range
            if level == ok:
                default_state = 2

        # Iterate all threshold and determine states
        for level, threshold_range in thresholds:
            highest_level = max(highest_level, level)
            # If ok threshold was specified, default state is critical according to spec
            # If value matches our threshold, we increment the status
            try:
                in_range = new_threshold_syntax.check_range(
                    metric.value, threshold_range)
            except pynag.errors.PynagError:
                self.set_summary(
                    "Could not parse threshold %s=%s for metric %s" %
                    (state_text[
                     level], threshold_range, metric_name)
                )
                self.set_long_output(
                    "Thresholds should be in the format metric=<metric_name>,ok=0..90,warning=90..95")
                self.add_long_output("Example: ")
                self.add_long_output(
                    "--th metric=load,ok=0..1,warning=1..5,critical=5..inf")
                self.status(unknown)
                self.exit()
            if in_range:
                metric_status = max(metric_status, level)
                self.debug('%s is within %s range "%s"' %
                           (metric_name, state_text[level], threshold_range))
                if level == ok:
                    self.debug(
                        "OK threshold matches, not checking any more thresholds")
                    metric_status = ok
                    break
            else:
                self.debug('%s is outside %s range "%s"' %
                           (metric_name, state_text[level], threshold_range))

        # If no thresholds matched, set a default return code
        if metric_status < 0:
            metric_status = default_state

        # OK's go to long output, errors go directly to summary
        self.add_status(metric_status)
        message = '%s on %s' % (state_text[metric_status], metric_name)

        # Errors are added to the summary:
        if metric_status > 0:
            self.add_summary(message)

        if self.verbose is True:
            self.add_long_output(message)

    def check_all_metrics(self):
        """ Checks all metrics (add_metric() against any thresholds set in self.options.thresholds or with --threshold from commandline)"""
        checked_metrics = []
        for threshold in self.thresholds:
            parsed_threshold = new_threshold_syntax.parse_threshold(threshold)
            metric_name = parsed_threshold['metric']
            thresholds = parsed_threshold['thresholds']
            self.check_metric(metric_name, thresholds)
            checked_metrics.append(metric_name)

        # Lets look at metrics that were not specified on the command-line but might have a default
        # threshold specified with their metric data
        for i in self._perfdata.metrics:
            if i.label in checked_metrics:
                continue
            thresholds = []

            if i.warn != '':
                thresholds.append((warning, i.warn))
            if i.crit != '':
                thresholds.append((critical, i.crit))
            self.check_metric(i.label, thresholds)

    def run_function(self, function, *args, **kwargs):
        """ Executes "function" and exits Nagios style with status "unkown"
        if there are any exceptions. The stacktrace will be in long_output.

        Example:
        >>> p = PluginHelper()
        >>> p.add_status('ok')
        >>> p.get_status()
        0
        >>> p.add_status('okay')
        Traceback (most recent call last):
        ...
        Exception: Invalid status supplied "okay"
        >>> p.run_function( p.add_status, 'warning' )
        >>> p.get_status()
        1
        >>> p.run_function( p.add_status, 'okay' )
        Traceback (most recent call last):
        ...
        SystemExit: 3
        """
        try:
            function(*args, **kwargs)
        except Exception:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            exit_code = unknown
            # traceback.print_exc(file=sys.stdout)
            summary = "Unhandled '%s' exception while running plugin (traceback below)" % exc_type
            long_output = traceback.format_exc()
            self.exit(exit_code=exit_code, summary=summary,
                      long_output=long_output, perfdata='')

    def debug(self, message):  # pragma: no cover
        if self.show_debug is True:
            self.add_long_output("debug: %s" % message)

    def __str__(self):
        """
        >>> p = PluginHelper()
        >>> p.add_status(ok)
        >>> p.add_summary('Test')
        >>> print(p)
        OK - Test
        """
        return self.get_plugin_output()

    def __repr__(self):
        return self.get_plugin_output(long_output='', perfdata='')

# For backwards compatibility:
check_range = classic_threshold_syntax.check_range
check_threshold = classic_threshold_syntax.check_threshold