This file is indexed.

/usr/share/check_mk/checks/if.include is in check-mk-server 1.2.8p16-1ubuntu0.1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  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
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2014             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk 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 in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# Functions and definitions used by if and if64

if_inventory_porttypes = [ '6', '32', '62', '117', '127', '128', '129', '180', '181', '182', '205','229' ]
if_inventory_portstates = [ '1' ]
if_inventory_uses_description = False
if_inventory_uses_alias = False
if_inventory_pad_portnumbers = True
if_inventory_monitor_speed = True
if_inventory_monitor_state = True
inventory_if_rules = []

factory_settings["if_default_levels"] = {
    "errors" : (0.01, 0.1),
}


# Grouping of if ports
#if_groups = [
#   ( [{"name" : "VLAN", "iftype" : 53, "single" : True}], [ ], ALL_HOSTS ),
#   ( [{"name" : "Group WLAN", "iftype" : 6, "single" : True}], [ "lan" ], ALL_HOSTS )
#   ]
#
if_groups = []

# Obsolete variable, but needed as contained in autochecks of
# older checks. We need to keep this up for a few years...
if_default_error_levels = factory_settings["if_default_levels"]["errors"]
if_default_traffic_levels = None, None
if_default_average = None

if_disable_if64_hosts = [] # Binary host list for disabling if64 on some broken devices

def if64_disabled(hostname):
    return in_binary_hostlist(hostname, if_disable_if64_hosts)


def fix_if_64_highspeed(info):
    for line in info:
        if type(line[3]) in [ str, unicode ]: # not yet converted
            line[3] = saveint(line[3]) * 1000000


# Remove 0 bytes from strings. They lead to problems e.g. here:
# On windows hosts the labels of network interfaces in oid
# iso.3.6.1.2.1.2.2.1.2.1 are given as hex strings with tailing
# 0 byte. When this string is part of the data which is sent to
# the nagios pipe all chars after the 0 byte are stripped of.
# Stupid fix: Remove all 0 bytes. Hope this causes no problems.
def cleanup_if_strings(s):
    if s and s != '':
        return "".join([ c for c in s if c not in nagios_illegal_chars+chr(0) ]).strip()
    else:
        return s

# make sure, that configuration variable is present in precompiled host checks
check_config_variables.append("nagios_illegal_chars")

# Name of state (lookup SNMP enum)
def if_statename(st):
    names = {
        '1': 'up',
        '2': 'down',
        '3': 'testing',
        '4': 'unknown',
        '5': 'dormant',
        '6': 'not present',
        '7': 'lower layer down',
        '8': 'degraded',
        '9': 'admin down',
    }
    return names.get(st, st)

def if_extract_node(line, has_nodeinfo):
    if has_nodeinfo:
        return line[0], line[1:]
    else:
        return None, line

def if_item_matches(item, ifIndex, ifAlias, ifDescr):
    return item.lstrip("0") == ifIndex \
            or (item == "0" * len(item) and saveint(ifIndex) == 0) \
            or item == ifAlias \
            or item == ifDescr \
            or item == "%s %s" % (ifAlias, ifIndex) \
            or item == "%s %s" % (ifDescr, ifIndex)

# Pads port numbers with zeroes, so that items
# nicely sort alphabetically
def if_pad_with_zeroes(info, ifIndex, has_nodeinfo, pad_portnumbers):
    if has_nodeinfo:
        index = 1
    else:
        index = 0
    if pad_portnumbers:
        def get_index(line):
            if type(line[index]) == tuple:
                return line[index][1]
            else:
                return line[index]

        max_index = max([int(get_index(line)) for line in info])
        digits = len(str(max_index))
        return ("%0"+str(digits)+"d") % int(ifIndex)
    else:
        return ifIndex


def if_get_traffic_levels(params):
    # Transform old style traffic parameters to new CascadingDropdown based data format
    new_traffic = []
    if 'traffic' in params and type(params['traffic']) != list:
        warn, crit = params['traffic']
        if warn == None:
            new_traffic.append(('both', ('upper', (None, (None, None)))))
        elif type(warn) == int:
            new_traffic.append(('both', ('upper', ('abs', (warn, crit)))))
        elif type(warn) == float:
            new_traffic.append(('both', ('upper', ('perc', (warn, crit)))))

    if 'traffic_minimum' in params:
        warn, crit = params['traffic_minimum']
        if type(warn) == int:
            new_traffic.append(('both', ('lower', ('abs', (warn, crit)))))
        elif type(warn) == float:
            new_traffic.append(('both', ('lower', ('perc', (warn, crit)))))
        del params['traffic_minimum']

    if new_traffic:
        traffic_levels = new_traffic
    else:
        traffic_levels = params.get('traffic', [])

    # Now bring the levels in a structure which is easily usable for the check
    # and also convert direction="both" to single in/out entries
    levels = {
        ('in',  'upper'): (None, (None, None)),
        ('out', 'upper'): (None, (None, None)),
        ('in',  'lower'): (None, (None, None)),
        ('out', 'lower'): (None, (None, None)),
    }
    for level in traffic_levels:
        traffic_dir = level[0]
        up_or_low   = level[1][0]
        level_type  = level[1][1][0]
        level_value = level[1][1][1]

        if traffic_dir == 'both':
            levels[('in', up_or_low)]  = (level_type, level_value)
            levels[('out', up_or_low)] = (level_type, level_value)
        else:
            levels[(traffic_dir, up_or_low)] = (level_type, level_value)

    return levels


def get_specific_traffic_levels(general_traffic_levels, unit, ref_speed, assumed_speed_in, assumed_speed_out):
    traffic_levels = {}
    for (traffic_dir, up_or_low), (level_type, levels) in general_traffic_levels.items():
        if type(levels) != tuple:
            traffic_levels[(traffic_dir, 'predictive')] = levels
            traffic_levels[(traffic_dir, up_or_low, 'warn')] = None
            traffic_levels[(traffic_dir, up_or_low, 'crit')] = None
            continue # don't convert predictive levels config
        else:
            warn, crit = levels

        for what, level_value in [('warn', warn), ('crit', crit)]:
            # If the measurement unit is set to bit and the bw levels
            # are of type absolute, convert these 'bit' entries to byte
            # still reported as bytes to stay compatible with older rrd data
            if unit == 'Bit' and level_type == 'abs':
                level_value = level_value / 8
            elif level_type == 'perc':
                # convert percentages to absolute values. Use either the assumed speed
                # or the reference speed. When none of both are available, ignore
                # the percentual levels
                if traffic_dir == 'in' and assumed_speed_in:
                    level_value = level_value / 100.0 * assumed_speed_in / 8
                elif traffic_dir == 'out' and assumed_speed_out:
                    level_value = level_value / 100.0 * assumed_speed_out / 8
                elif ref_speed:
                    level_value = level_value / 100.0 * ref_speed
                else:
                    level_value = None

            traffic_levels[(traffic_dir, up_or_low, what)] = level_value # bytes
    return traffic_levels

def inventory_if_common(info, has_nodeinfo = False):
    if has_nodeinfo:
        length = 21
    else:
        length = 20
    if len(info) == 0 or len(info[0]) != length:
        return []

    settings            = host_extra_conf_merged(g_hostname, inventory_if_rules)
    uses_description    = settings.get('use_desc', if_inventory_uses_description)
    uses_alias          = settings.get('use_alias', if_inventory_uses_alias)
    # Need to copy porttypes as the discovery function appends to the list below.
    # The check must not modify the global if_inventory_porttypes configuration variable.
    porttypes           = settings.get('porttypes', if_inventory_porttypes)[:]
    portstates          = settings.get('portstates', if_inventory_portstates)
    match_alias         = settings.get('match_alias')
    match_desc          = settings.get('match_desc')
    pad_portnumbers     = settings.get('pad_portnumbers', if_inventory_pad_portnumbers)

    def port_match(name, what):
        if what == None:
            return True
        for r in what:
            if regex(r).match(name):
                return True
        return False

    # Allow main check to set no port type (e.g. hitachi_hnas_fc_if)
    porttypes.append("")

    pre_inventory        = []
    pre_inventory_groups = []
    group_patterns = {}

    for line in host_extra_conf(g_hostname, if_groups):
        for entry in line:
            group_patterns[entry["name"]] = entry

    seen_items  = set([])
    duplicate   = set([])
    have_groups = {}

    # Determine whether single, grouped or both
    for line in info:
        node, line = if_extract_node(line, has_nodeinfo)
        ifIndex, ifDescr, ifType, ifSpeed, ifOperStatus, ifInOctets, \
            inucast, inmcast, inbcast, ifInDiscards, ifInErrors, ifOutOctets, \
            outucast, outmcast, outbcast, ifOutDiscards, ifOutErrors, \
            ifOutQLen, ifAlias, ifPhysAddress = line

        # Windows NICs sends pairs of ifOperStatus and its Windows-Name instead
        # of just the ifOperStatus
        if type(ifOperStatus) == tuple:
            ifOperStatus = ifOperStatus[0]

        ifGroup = None
        if type(ifIndex) == tuple:
            ifGroup, ifIndex = ifIndex

        ifDescr = cleanup_if_strings(ifDescr)
        ifAlias = cleanup_if_strings(ifAlias)

        # Fix bug in brocade switches
        if ifIndex == '':
            continue

        # Fix bug in TP Link switches
        ifSpeed = saveint(ifSpeed)
        if ifSpeed > 9000000 * 100 * 1000:
            ifSpeed /= 1000000

        # compute item now - also for unmonitored ports - in order to see if it is unique.
        if uses_description and ifDescr:
            item = ifDescr
        elif uses_alias and ifAlias:
            item = ifAlias
        else:
            item = if_pad_with_zeroes(info, ifIndex, has_nodeinfo, pad_portnumbers)

        # Prepare grouped interfaces
        is_only_in_group = False
        for group_name, pattern in group_patterns.items():
            # Interfaces can be grouped by item and iftype
            match_item = "include_items" not in pattern or (tryint(item) in map(tryint, pattern["include_items"]))
            match_type = "iftype" not in pattern        or (pattern["iftype"] == saveint(ifType))
            if match_item and match_type:
                have_groups.setdefault(group_name, {"interfaces": []})
                for what in [ "iftype", "include_items" ]:
                    if pattern.get(what):
                        have_groups[group_name][what] = pattern.get(what)

                have_groups[group_name]["interfaces"].append((saveint(ifSpeed), ifOperStatus, ifType))
                if pattern.get("single"):
                    is_only_in_group = True

        # The agent output already set this interface to grouped
        if ifGroup:
            have_groups.setdefault(ifGroup, {"interfaces": [],
                                             "iftype": ifType,
                                             "include_items": []})
            have_groups[ifGroup]["interfaces"].append((saveint(ifSpeed), ifOperStatus, ifType))
            is_only_in_group = True

        # Prepare single interfaces
        if not is_only_in_group:
            if item in seen_items: # duplicate
                duplicate.add(item)
            seen_items.add(item)

            if ifType in porttypes and ifOperStatus in portstates and \
                port_match(ifAlias, match_alias) and port_match(ifDescr, match_desc):
                params = {}
                if if_inventory_monitor_state:
                    params["state"] = [ifOperStatus]

                if ifSpeed != "" and if_inventory_monitor_speed:
                    params["speed"] = int(ifSpeed)
                pre_inventory.append( (item, "%r" % params, int(ifIndex)) )

    # create pseudo interfaces out of groups
    for group_name, values in have_groups.items():
        # total maximum speed of all interfaces in this group
        total_speed = sum([pair[0] for pair in values["interfaces"]])
        # operation status, default is down(2)
        # if at least one is up(1) then up is considered as valid
        one_up = "1" in [pair[1] for pair in values["interfaces"]]
        group_operStatus = one_up and "1" or "2"

        if group_operStatus in portstates:
            params = { "aggregate": True }
            for what in [ "iftype", "include_items" ]:
                if what in values:
                    params[what] = values[what]

            if uses_description:
                params["aggr_member_item"] = "description"
            elif uses_alias:
                params["aggr_member_item"] = "alias"
            else:
                params["aggr_member_item"] = "index"

            if if_inventory_monitor_state:
                params["state"] = [group_operStatus]

            if ifSpeed != "" and if_inventory_monitor_speed:
                params["speed"] = total_speed

            # Note: the group interface index is always set to 1
            pre_inventory.append((group_name, "%r" % params, 1))

    inventory = []
    # Check for duplicate items (e.g. when using Alias as item and the alias is not unique)
    for item, params, index in pre_inventory:
        if item in duplicate:
            new_item = "%s %d" % (item, index)
        else:
            new_item = item
        inventory.append((new_item, params))

    return inventory

def check_if_common(item, params, info, has_nodeinfo = False, group_name = "Group"):
    # If this item is in an ifgroup create a pseudo interface and pass its data to the common instance
    # This is done by simply adding the additional group_info data to the already existing info table
    if params.get("aggregate"):
        group_members = []
        matching_interfaces = []

        for element in info:
            node, line = if_extract_node(element, has_nodeinfo)
            ifIndex, ifDescr, ifType, ifSpeed, ifOperStatus, ifInOctets, \
                inucast, inmcast, inbcast, ifInDiscards, ifInErrors, ifOutOctets, \
                outucast, outmcast, outbcast, ifOutDiscards, ifOutErrors, \
                ifOutQLen, ifAlias, ifPhysAddress = line

            ifGroup = None
            if type(ifIndex) == tuple:
                ifGroup, ifIndex = ifIndex

            service_name_type = params.get("aggr_member_item")
            if service_name_type == "description":
                if_member_item = ifDescr
            elif service_name_type == "alias":
                if_member_item = ifAlias
            else: # index
                pad_portnumbers = item[0] == '0'
                if_member_item = if_pad_with_zeroes(info, ifIndex, has_nodeinfo, pad_portnumbers)

            if ifGroup and ifGroup == item:
                matching_interfaces.append((if_member_item, element))
            else:
                # The iftype and include_items parameters are further restrictions
                # If none of them are set, the interface is added to the group
                add_interface = True # This approach is easier to comprehend..
                # tryint -> force "01" and "1" to be identical.
                if params.get("include_items") != None and tryint(if_member_item) not in map(tryint, params["include_items"]):
                    add_interface = False
                elif params.get("iftype") != None and saveint(ifType) != params["iftype"]:
                    add_interface = False
                if add_interface:
                    matching_interfaces.append((if_member_item, element))

        # Accumulate info over matching_interfaces
        wrapped = False
        this_time = time.time()

        group_info = {
            "ifSpeed"      : 0, "ifInOctets"    : 0, "inucast"     : 0, "inmcast"   : 0, "inbcast" : 0,
            "ifInDiscards" : 0, "ifInErrors"    : 0, "ifOutOctets" : 0, "outucast"  : 0, "outmcast" : 0,
            "outbcast"     : 0, "ifOutDiscards" : 0, "ifOutErrors" : 0, "ifOutQLen" : 0
        }

        for (if_member_item, element) in matching_interfaces:
            node, line = if_extract_node(element, has_nodeinfo)
            ifIndex, ifDescr, ifType, ifSpeed, ifOperStatus, ifInOctets, \
                inucast, inmcast, inbcast, ifInDiscards, ifInErrors, ifOutOctets, \
                outucast, outmcast, outbcast, ifOutDiscards, ifOutErrors, \
                ifOutQLen, ifAlias, ifPhysAddress = line

            # Windows NICs sends pairs of ifOperStatus and its Windows-Name instead
            # of just the ifOperStatus
            if type(ifOperStatus) == tuple:
                ifOperStatus, ifOperStatusName = ifOperStatus
            else:
                ifOperStatusName = if_statename(ifOperStatus)

            if has_nodeinfo and node:
                return 3, "Interface grouping is not supported for clusters."

            ifGroup = None
            if type(ifIndex) == tuple:
                ifGroup, ifIndex = ifIndex

            group_members.append({"name": if_member_item, "state": ifOperStatus, "state_name" : ifOperStatusName})
            perfdata = []

            # Only these values are packed into counters
            # We might need to enlarge this table
            # However, more values leads to more MKCounterWrapped...
            for name, counter in [
                ( "in",        ifInOctets),
                ( "inucast",   inucast),
                ( "inmcast",   inmcast),
                ( "inbcast",   inbcast),
                ( "indisc",    ifInDiscards),
                ( "inerr",     ifInErrors),

                ( "out",       ifOutOctets),
                ( "outucast",  outucast),
                ( "outmcast",  outmcast),
                ( "outbcast",  outbcast),
                ( "outdisc",   ifOutDiscards),
                ( "outerr",    ifOutErrors) ]:
                try:
                    get_rate("if.%s.%s.%s" % (name, item, if_member_item), this_time, saveint(counter), onwrap=RAISE)
                except MKCounterWrapped:
                    wrapped = True
                    # continue, other counters might wrap as well

            # Add interface info to group info
            group_info["ifSpeed"]       += ifOperStatus == "1" and saveint(ifSpeed) or 0
            group_info["ifInOctets"]    += saveint(ifInOctets)
            group_info["inucast"]       += saveint(inucast)
            group_info["inmcast"]       += saveint(inmcast)
            group_info["inbcast"]       += saveint(inbcast)
            group_info["ifInDiscards"]  += saveint(ifInDiscards)
            group_info["ifInErrors"]    += saveint(ifInErrors)
            group_info["ifOutOctets"]   += saveint(ifOutOctets)
            group_info["outucast"]      += saveint(outucast)
            group_info["outmcast"]      += saveint(outmcast)
            group_info["outbcast"]      += saveint(outbcast)
            group_info["ifOutDiscards"] += saveint(ifOutDiscards)
            group_info["ifOutErrors"]   += saveint(ifOutErrors)
            group_info["ifOutQLen"]     += saveint(ifOutQLen)

            group_info["ifType"] = ifType # This is the fallback ifType if none is set in the parameters

        # Append an additional entry to the info table containing the calculated group_info
        num_up = 0
        for (if_member_item, element) in matching_interfaces:
            node, line = if_extract_node(element, has_nodeinfo)
            ifIndex, ifDescr, ifType, ifSpeed, ifOperStatus, ifInOctets, \
                inucast, inmcast, inbcast, ifInDiscards, ifInErrors, ifOutOctets, \
                outucast, outmcast, outbcast, ifOutDiscards, ifOutErrors, \
                ifOutQLen, ifAlias, ifPhysAddress = line

            if ifOperStatus == '1' or (
                type(ifOperStatus) == tuple and ifOperStatus[0] == '1'):
                num_up += 1

        if num_up == len(matching_interfaces):
            group_operStatus = "1" # up
        elif num_up > 0:
            group_operStatus = "8" # degraded
        else:
            group_operStatus = "2" # down

        alias_info = []
        if params.get("iftype"):
            alias_info.append("iftype %s" % params["iftype"])
        if params.get("include_items"):
            alias_info.append("%d grouped interfaces" % len(matching_interfaces))

        if has_nodeinfo:
            group_entry = [None]
        else:
            group_entry = []

        if params.get("ifType"):
            group_info["ifType"] = params["ifType"]

        group_entry += [
                    "ifgroup%s" % item,         # ifIndex
                    item,                       # ifDescr
                    group_info["ifType"],       # ifType
                    group_info["ifSpeed"],      # ifSpeed
                    group_operStatus,           # ifOperStatus
                    group_info["ifInOctets"],   # ifInOctets
                    group_info["inucast"],      # inucast
                    group_info["inmcast"],      # inmcast
                    group_info["inbcast"],      # inbcast
                    group_info["ifInDiscards"], # ifInDiscards
                    group_info["ifInErrors"],   # ifInErrors

                    group_info["ifOutOctets"],  # ifOutOctets
                    group_info["outucast"],     # outucast
                    group_info["outmcast"],     # outmcast
                    group_info["outbcast"],     # outbcast
                    group_info["ifOutDiscards"],# ifOutDiscards
                    group_info["ifOutErrors"],  # ifOutErrors
                    group_info["ifOutQLen"],    # ifOutQLen
                    " and ".join(alias_info),
                    "",                         # ifPhysAddress
        ]

        # If applicable, signal the check_if_common_single if the counter of the
        # given interface has wrapped. Actually a wrap of the if group itself is unlikely,
        # however any counter wrap of one of its members causes the accumulation being invalid
        return check_if_common_single(item, params, [group_entry], wrapped,
                     has_nodeinfo = has_nodeinfo, group_members = group_members, group_name = group_name)

    return check_if_common_single(item, params, info, has_nodeinfo=has_nodeinfo, group_name = group_name)

# TODO: Check what the relationship between Errors, Discards, and ucast/mcast actually is.
# One case of winperf_if appeared to indicate that in that case Errors = Discards.

def check_if_common_single(item, params, info, force_counter_wrap = False,
                           has_nodeinfo = False, group_members = None, group_name = "Group"):
    # Params now must be a dict. Some keys might
    # be set to None
    targetspeed        = params.get("speed")
    assumed_speed_in   = params.get("assumed_speed_in")
    assumed_speed_out  = params.get("assumed_speed_out")
    targetstate        = params.get("state")
    average            = params.get("average")
    unit               = params.get("unit") in ["Bit", "bit"] and "Bit" or "B"
    unit_multiplier    = unit == "Bit" and 8.0 or 1.0
    cluster_items      = {}

    # error checking might be turned off
    if params["errors"]:
        err_warn, err_crit = params["errors"]
    else:
        err_warn, err_crit = None, None

    # broadcast storm detection is turned off by default
    if "nucasts" in params:
        nucast_warn, nucast_crit = params["nucasts"]
    else:
        nucast_warn, nucast_crit = None, None

    # Convert the traffic related levels to a common format
    general_traffic_levels = if_get_traffic_levels(params)

    for line in info:
        node, line = if_extract_node(line, has_nodeinfo)
        ifIndex, ifDescr, ifType, ifSpeed, ifOperStatus, ifInOctets,  \
            inucast, inmcast, inbcast, ifInDiscards, ifInErrors, ifOutOctets, \
            outucast, outmcast, outbcast, ifOutDiscards, ifOutErrors, \
            ifOutQLen, ifAlias, ifPhysAddress = line

        # Windows NICs sends pairs of ifOperStatus and its Windows-Name instead
        # of just the ifOperStatus
        if type(ifOperStatus) == tuple:
            ifOperStatus, ifOperStatusName = ifOperStatus
        else:
            ifOperStatusName = if_statename(ifOperStatus)

        ifGroup = None
        if type(ifIndex) == tuple:
            ifGroup, ifIndex = ifIndex

        ifDescr = cleanup_if_strings(ifDescr)
        ifAlias = cleanup_if_strings(ifAlias)

        if if_item_matches(item, ifIndex, ifAlias, ifDescr):
            if group_members:
                # The detailed group info is added later on
                infotext = group_name + " Status "
            else:
                if "infotext_format" in params:
                    bracket_info = ""
                    if   params["infotext_format"] == "alias":
                        bracket_info = ifAlias
                    elif params["infotext_format"] == "description":
                        bracket_info = ifDescr
                    elif params["infotext_format"] == "alias_and_description":
                        bracket_info = []
                        ifAlias and bracket_info.append(ifAlias)
                        ifDescr and bracket_info.append(ifDescr)
                        bracket_info = ", ".join(bracket_info)
                    elif params["infotext_format"] == "alias_or_description":
                        bracket_info = ifAlias and ifAlias or ifDescr
                    elif params["infotext_format"] == "desription_or_alias":
                        bracket_info = ifDescr and ifDescr or ifAlias

                    if bracket_info:
                        infotext = "[%s]" % bracket_info
                    else:
                        infotext = ""
                else:
                    # Display port number or alias in infotext if that is not part
                    # of the service description anyway
                    if item.lstrip("0") == ifIndex \
                        and (item == ifAlias or ifAlias == '') \
                        and (item == ifDescr or ifDescr == ''): # description trivial
                        infotext = ""
                    elif item == "%s %s" % (ifAlias, ifIndex) and ifDescr != '': # non-unique Alias
                        infotext = "[%s/%s]" % (ifAlias, ifDescr)
                    elif item != ifAlias and ifAlias != '': # alias useful
                        infotext = "[%s] " % ifAlias
                    elif item != ifDescr and ifDescr != '': # description useful
                        infotext = "[%s] " % ifDescr
                    else:
                        infotext = "[%s] " % ifIndex

                if node != None:
                    infotext = "%son %s: " % ( infotext, node )

            state = 0

            if targetstate and  \
                (ifOperStatus != targetstate
                and not (type(targetstate) in [ list, tuple ] and ifOperStatus in targetstate)):
                state = 2
                infotext += "(%s)(!!) " % ifOperStatusName
            else:
                infotext += "(%s) " % ifOperStatusName

            if group_members:
                infotext = infotext[:-1] # remove last space
                extra_info = ", Members: "
                member_info = []
                for member in group_members:
                    member_info.append("%s (%s)" % (member["name"], member["state_name"]))
                infotext += extra_info + "[%s] " % ", ".join(member_info)

            # prepare reference speed for computing relative bandwidth usage
            speed = saveint(ifSpeed)
            if speed:
                if speed > 9 * 1000 * 1000 * 1000 * 1000:
                    speed /= (1000 * 1000)
                ref_speed = speed / 8.0
            elif targetspeed:
                ref_speed = targetspeed / 8.0
            else:
                ref_speed = None


	    if ifPhysAddress:
                if type(ifPhysAddress) != list:
                    mac_bytes = map(ord, ifPhysAddress)
                else:
                    mac_bytes = ifPhysAddress
                mac = ":".join(["%02s" % hex(m)[2:] for m in mac_bytes]).replace(' ', '0')
                infotext += 'MAC: %s, ' % mac

            # Check speed settings of interface, but only if speed information
            # is available. This is not always the case.
            if speed:
                infotext += get_nic_speed_human_readable(speed)
                if not targetspeed is None and speed != targetspeed:
                    infotext += " (wrong speed, expected: %s)(!)" % get_nic_speed_human_readable(targetspeed)
                    state = max(state, 1)
            elif targetspeed:
                infotext += "assuming %s" % get_nic_speed_human_readable(targetspeed)
            else:
                infotext += "speed unknown"

            # Convert the traffic levels to interface specific levels, for example where the percentage
            # levels are converted to absolute levels or assumed speeds of an interface are treated correctly
            traffic_levels = get_specific_traffic_levels(general_traffic_levels, unit, ref_speed, assumed_speed_in, assumed_speed_out)

            # Speed in bytes
            speed_b_in  = assumed_speed_in  and assumed_speed_in / 8  or ref_speed
            speed_b_out = assumed_speed_out and assumed_speed_out / 8 or ref_speed

            #
            # All internal values within ths check after this point are bytes, not bits!
            #

            # When the interface is reported as down, there is no need to try to handle,
            # the performance counters. Most devices do reset the counter values to zero,
            # but we spotted devices, which do report error packes even for down interfaces.
            # To deal with it, we simply skip over all performance counter checks for down
            # interfaces.
            if str(ifOperStatus) == "2":
                return state, infotext

            # Performance counters
            this_time = time.time()
            rates = []
            wrapped = False
            perfdata = []
            for name, counter, warn, crit, mmin, mmax in [
                ( "in",        ifInOctets, traffic_levels[('in', 'upper', 'warn')], traffic_levels[('in', 'upper', 'crit')], 0, speed_b_in),
                ( "inucast",   inucast, None, None, None, None),
                ( "innucast",  saveint(inmcast) + saveint(inbcast), nucast_warn, nucast_crit, None, None),
                ( "indisc",    ifInDiscards, None, None, None, None),
                ( "inerr",     ifInErrors, err_warn, err_crit, None, None),

                ( "out",       ifOutOctets, traffic_levels[('out', 'upper', 'warn')], traffic_levels[('out', 'upper', 'crit')], 0, speed_b_out),
                ( "outucast",  outucast, None, None, None, None),
                ( "outnucast", saveint(outmcast) + saveint(outbcast), nucast_warn, nucast_crit, None, None),
                ( "outdisc",   ifOutDiscards, None, None, None, None),
                ( "outerr",    ifOutErrors, err_warn, err_crit, None, None) ]:

                try:
                    if node == None:
                        rate = get_rate("if.%s.%s" % (name, item), this_time, saveint(counter), onwrap=RAISE)
                        if force_counter_wrap:
                            raise MKCounterWrapped("Forced counter wrap")
                    else: # clustered check needs one counter per variable, item AND NODE
                        rate = get_rate("if.%s.%s.%s" % (node, name, item), this_time, saveint(counter), onwrap=RAISE)
                        if force_counter_wrap:
                            raise MKCounterWrapped("Forced counter wrap")
                    rates.append(rate)
                    perfdata.append( (name, rate, warn, crit, mmin, mmax) )
                except MKCounterWrapped:
                    wrapped = True
                    # continue, other counters might wrap as well

            # if at least one counter wrapped, we do not handle the counters at all
            if wrapped:
                # If there is a threshold on the bandwidth, we cannot proceed
                # further (the check would be flapping to green on a wrap)
                if any(traffic_levels.values()):
                    raise MKCounterWrapped("Counter wrap, skipping checks this time")
                perfdata = []
            else:
                perfdata.append(("outqlen", saveint(ifOutQLen),"","", unit == "Bit" and "0.0" or "0"))
                def format_value(value):
                    if unit == "Bit":
                        return get_nic_speed_human_readable(value*8)
                    else:
                        return "%s/s" % get_bytes_human_readable(value)

                # loop over incoming and outgoing traffic
                for what, errorrate, urate, nurate, traffic, speed in \
                   [ ("in",  rates[4], rates[1], rates[2], rates[0], speed_b_in),
                     ("out", rates[9], rates[6], rates[7], rates[5], speed_b_out) ]:

                    infotext += ", %s: %s" % (what, format_value(traffic))

                    if (what, 'predictive') in traffic_levels:
                        params = traffic_levels[(what, 'predictive')]
                        bw_warn, bw_crit = None, None
                    else:
                        bw_warn     = traffic_levels[(what, 'upper', 'warn')]
                        bw_crit     = traffic_levels[(what, 'upper', 'crit')]
                        bw_warn_min = traffic_levels[(what, 'lower', 'warn')]
                        bw_crit_min = traffic_levels[(what, 'lower', 'crit')]
                        params = (bw_warn, bw_crit, bw_warn_min, bw_crit_min)

                    if speed:
                        perc_used = 100.0 * traffic / speed

                        assumed_info = ""
                        if assumed_speed_in or assumed_speed_out:
                            assumed_info = "/" + format_value(speed)
                        infotext += "(%.1f%%%s)" % (perc_used, assumed_info)

                    # handle computation of average
                    if average:
                        traffic_avg = get_average("if.%s.%s.avg" % (what, item), this_time, traffic, average)
                        infotext += ", %dmin avg: %s" % (average, format_value(traffic_avg))
                        dsname = "%s_avg_%d" % (what, average)
                        perfdata.append((dsname, traffic_avg, bw_warn, bw_crit, 0, speed))
                        traffic = traffic_avg # apply levels to average traffic
                    else:
                        dsname = what

                    # Check bandwidth thresholds incl. prediction
                    result = check_levels(traffic, dsname, params, statemarkers=True)
                    state = max(state, result[0])
                    infotext += result[1]
                    perfdata += result[2]

                    # check percentage of error packets
                    pacrate = urate + nurate + errorrate
                    if pacrate > 0.0: # any packets transmitted?
                        errperc = 100.0 * errorrate / pacrate
                        if errperc > 0:
                            infotext += ", %s-errors: %.2f%%" % (what, errperc)
                            if type(err_crit) == float: # percentual levels
                                if errperc >= err_crit:
                                    state = 2
                                    infotext += "(!!) >= %s%%" % str(err_crit)
                                elif errperc >= err_warn:
                                    state = max(state, 1)
                                    infotext += "(!) >= %s%%" % str(err_warn)
                            elif type(err_crit) == int: # absolute levels
                                if errorrate >= err_crit:
                                    state = 2
                                    infotext += ", %s-error packets: %d (!!) >= %s" % (what, errorrate, err_crit)
                                elif errorrate >= err_warn:
                                    state = max(state, 1)
                                    infotext += ", %s-errors packets: %d (!!) >= %s" % (what, errorrate, err_warn)


                    # check rate of non-unicast packets
                    if nucast_crit or nucast_warn:
                        infotext += ", %s non-unicast packets %.2f/s" % (what, nurate)

                        if nucast_crit and nurate >= nucast_crit:
                            state = 2
                            infotext += "(!!) >= " + str(nucast_crit)
                        elif nucast_warn and nurate >= nucast_warn:
                            state = max(state,1)
                            infotext += "(!) >= " + str(nucast_warn)

            if node:
                cluster_items[node] = ( state, infotext, perfdata )
            else:
                return (state, infotext, perfdata)

    # if system is a cluster we have more than one line per item with
    # different node, results are collected in cluster_items
    # we choose the node with the highest outgoing traffic
    # since in a cluster environment this is likely the node
    # which is master
    if cluster_items:
        maxval = 0
        choosen_node = None
        for node, result in cluster_items.items():
            state, infotext, perfdata = result
            for entry in perfdata:
                name, value = entry[:2]
                if name == "out":
                    maxval = max(maxval, value)
                    if maxval == value:
                        choosen_node = node
        # In case that each node has a counter wrap for
        # out, we use the last note from the list as source
        if not choosen_node:
            choosen_node = node
        return cluster_items[choosen_node]

    return (3, "no such interface")



# possible port types are:

# other(1), regular1822(2), hdh1822(3), ddnX25(4), rfc877x25(5),
# ethernetCsmacd(6), iso88023Csmacd(7), iso88024TokenBus(8),
# iso88025TokenRing(9), iso88026Man(10), starLan(11), proteon10Mbit(12),
# proteon80Mbit(13), hyperchannel(14), fddi(15), lapb(16), sdlc(17), ds1(18),
# e1(19), basicISDN(20), primaryISDN(21), propPointToPointSerial(22),
# ppp(23), softwareLoopback(24), eon(25), ethernet3Mbit(26),
# nsip(27), slip(28), ultra(29), ds3(30), sip(31), frameRelay(32),
# rs232(33), para(34), arcnet(35), arcnetPlus(36), atm(37), miox25(38),
# sonet(39), x25ple(40), iso88022llc(41), localTalk(42), smdsDxi(43),
# frameRelayService(44), v35(45), hssi(46), hippi(47), modem(48),
# aal5(49), sonetPath(50), sonetVT(51), smdsIcip(52), propVirtual(53),
# propMultiplexor(54), ieee80212(55), fibreChannel(56), hippiInterface(57),
# frameRelayInterconnect(58), aflane8023(59), aflane8025(60), cctEmul(61),
# fastEther(62), isdn(63), v11(64), v36(65), g703at64k(66), g703at2mb(67),
# qllc(68), fastEtherFX(69), channel(70), ieee80211(71), ibm370parChan(72),
# escon(73), dlsw(74), isdns(75), isdnu(76), lapd(77), ipSwitch(78),
# rsrb(79), atmLogical(80), ds0(81), ds0Bundle(82), bsc(83), async(84),
# cnr(85), iso88025Dtr(86), eplrs(87), arap(88), propCnls(89), hostPad(90),
# termPad(91), frameRelayMPI(92), x213(93), adsl(94), radsl(95), sdsl(96),
# vdsl(97), iso88025CRFPInt(98), myrinet(99), voiceEM(100), voiceFXO(101),
# voiceFXS(102), voiceEncap(103), voiceOverIp(104), atmDxi(105), atmFuni(106),
# atmIma(107), pppMultilinkBundle(108), ipOverCdlc(109), ipOverClaw(110),
# stackToStack(111), virtualIpAddress(112), mpc(113), ipOverAtm(114),
# iso88025Fiber(115), tdlc(116), gigabitEthernet(117), hdlc(118), lapf(119),
# v37(120), x25mlp(121), x25huntGroup(122), trasnpHdlc(123), interleave(124),
# fast(125), ip(126), docsCableMaclayer(127), docsCableDownstream(128),
# docsCableUpstream(129), a12MppSwitch(130), tunnel(131), coffee(132),
# ces(133), atmSubInterface(134), l2vlan(135), l3ipvlan(136), l3ipxvlan(137),
# digitalPowerline(138), mediaMailOverIp(139), dtm(140), dcn(141),
# ipForward(142), msdsl(143), ieee1394(144), if-gsn(145), dvbRccMacLayer(146),
# dvbRccDownstream(147), dvbRccUpstream(148), atmVirtual(149), mplsTunnel(150),
# srp(151), voiceOverAtm(152), voiceOverFrameRelay(153), idsl(154),
# compositeLink(155), ss7SigLink(156), propWirelessP2P(157), frForward(158),
# rfc1483(159), usb(160), ieee8023adLag(161), bgppolicyaccounting(162),
# frf16MfrBundle(163), h323Gatekeeper(164), h323Proxy(165), mpls(166),
# mfSigLink(167), hdsl2(168), shdsl(169), ds1FDL(170), pos(171), dvbAsiIn(172),
# dvbAsiOut(173), plc(174), nfas(175), tr008(176), gr303RDT(177), gr303IDT(178),
# isup(179), propDocsWirelessMaclayer(180), propDocsWirelessDownstream(181),
# propDocsWirelessUpstream(182), hiperlan2(183), propBWAp2Mp(184),
# sonetOverheadChannel(185), digitalWrapperOverheadChannel(186),
# aal2(187), radioMAC(188), atmRadio(189), imt(190), mvl(191), reachDSL(192),
# frDlciEndPt(193), atmVciEndPt(194), opticalChannel(195), opticalTransport(196),
# propAtm(197), voiceOverCable(198), infiniband(199), teLink(200), q2931(201),
# virtualTg(202), sipTg(203), sipSig(204), docsCableUpstreamChannel(205),
# econet(206), pon155(207), pon622(208), bridge(209), linegroup(210),
# voiceEMFGD(211), voiceFGDEANA(212), voiceDID(213), mpegTransport(214),
# sixToFour(215), gtp(216), pdnEtherLoop1(217), pdnEtherLoop2(218),
# opticalChannelGroup(219), homepna(220), gfp(221), ciscoISLvlan(222),
# actelisMetaLOOP(223), fcipLink(224), rpr(225), qam(226), lmp(227),
# cblVectaStar(228), docsCableMCmtsDownstream(229), adsl2(230)