This file is indexed.

/usr/share/check_mk/checks/if.include is in check-mk-server 1.2.6p12-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
#!/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-
# ails.  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)

# 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': 'notPresent',
              '7': 'lowerLayerDown' }
    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):
    if has_nodeinfo:
        index = 1
    else:
        index = 0
    if if_inventory_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 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)
    porttypes           = settings.get('porttypes', if_inventory_porttypes)
    portstates          = settings.get('portstates', if_inventory_portstates)
    match_alias         = settings.get('match_alias')

    def alias_matches(alias):
        if match_alias == None:
            return True
        for regex in match_alias:
            if get_regex(regex).match(alias):
                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

        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)

        # 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 = not pattern.get("include_items") or (item in pattern["include_items"])
            match_type = not pattern.get("iftype")        or (pattern["iftype"] == saveint(ifType))
            if match_item and match_type:
                have_groups.setdefault(group_name, {"interfaces": [],
                                                    "iftype": pattern.get("iftype"),
                                                    "include_items": pattern.get("include_items")})
                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 alias_matches(ifAlias):
                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 = { "iftype": values["iftype"],
                       "include_items": values["include_items"],
                       "aggregate": True }

            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):
    # 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"):
        matching_interfaces = []
        node_offset = has_nodeinfo and 1 or 0
        def get_interface_item(line):
            ifIndex = line[ 0 + node_offset]
            if type(ifIndex) == tuple:
                ifGroup, ifIndex = ifIndex

            ifDescr = line[ 1 + node_offset]
            ifAlias = line[18 + node_offset]
            if if_inventory_uses_description and ifDescr:
                if_item = ifDescr
            elif if_inventory_uses_alias and ifAlias:
                if_item = ifAlias
            else:
                if_item = if_pad_with_zeroes(info, ifIndex, has_nodeinfo)
            return if_item

        for element in info:
            ifIndex = element[0 + node_offset]
            ifGroup = None
            if type(ifIndex) == tuple:
                ifGroup, ifIndex = ifIndex

            if ifGroup and ifGroup == item:
                matching_interfaces.append(element)
            else:
                match_item = not params.get("include_items") or (get_interface_item(element) in params["include_items"])
                match_type = not params.get("iftype")        or (params["iftype"] == saveint(element[2 + node_offset]))
                if match_item and match_type:
                    matching_interfaces.append(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 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

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

            if_item = get_interface_item(element)
            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_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"]       += saveint(ifSpeed)
            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)



        # Append an additional entry to the info table containing the calculated group_info
        one_up = "1" in [element[4] for element in matching_interfaces]
        group_operStatus = one_up and "1" or "2"

        alias_info = []
        if params.get("iftype"):
            alias_info.append("iftype %s" % params["iftype"])
        if params.get("include_items"):
            alias_info.append("grouped items")

        group_entry = [
                    "ifgroup%s" % item,         # ifIndex
                    item,                       # ifDescr
                    params["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)

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

def check_if_common_single(item, params, info, force_counter_wrap = False, has_nodeinfo = False):
    # 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

    # Traffic checking might be turned off
    if "traffic" in params:
        bw_warn_param, bw_crit_param = params["traffic"]
    else:
        bw_warn_param, bw_crit_param = None, None

    # Traffic minimum checking might be turned off
    if "traffic_minimum" in params:
        bw_warn_min_param, bw_crit_min_param = params["traffic_minimum"]
    else:
        bw_warn_min_param, bw_crit_min_param = None, None

    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

        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):
            # 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

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


            # 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:
                mac = ":".join(["%02s" % hex(ord(m))[2:] for m in ifPhysAddress]).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"


            bw_warn, bw_crit         = bw_warn_param, bw_crit_param
            bw_warn_min, bw_crit_min = bw_warn_min_param, bw_crit_min_param
            # If the measurement unit is set to bit and the bw levels
            # are of type int convert these 'bit' entries to byte
            # still reported as bytes to stay compatible with older rrd data
            if unit == "Bit":
                if type(bw_warn_param) == int:
                    bw_warn     = bw_warn / 8
                if type(bw_crit_param) == int:
                    bw_crit     = bw_crit / 8
                if type(bw_warn_min_param) == int:
                    bw_warn_min     = bw_warn_min / 8
                if type(bw_crit_min_param) == int:
                    bw_crit_min     = bw_crit_min / 8

            # convert percentages to absolute values if levels are float
            # this is only possible if a reference speed is available.
            if ref_speed:
                if type(bw_warn_param) == float:
                    bw_warn = bw_warn_param / 100.0 * ref_speed # bytes
                if type(bw_crit_param) == float:
                    bw_crit = bw_crit_param / 100.0 * ref_speed # bytes
                if type(bw_warn_min_param) == float:
                    bw_warn_min = bw_warn_min_param / 100.0 * ref_speed # bytes
                if type(bw_crit_min_param) == float:
                    bw_crit_min = bw_crit_min_param / 100.0 * ref_speed # bytes
            # Ignore percentual levels if no reference speed is available
            else:
                if type(bw_warn_param) == float:
                    bw_warn = None
                if type(bw_crit_param) == float:
                    bw_crit = None
                if type(bw_warn_min_param) == float:
                    bw_warn_min = None
                if type(bw_crit_min_param) == float:
                    bw_crit_min = None


            bw_warn_in, bw_crit_in, bw_warn_out, bw_crit_out = [bw_warn, bw_crit] * 2
            bw_warn_min_in, bw_crit_min_in, bw_warn_min_out, bw_crit_min_out = [bw_warn_min, bw_crit_min] * 2
            for speed_in in [ assumed_speed_in, assumed_speed_out ]:
                if not speed_in:
                    continue
                if type(bw_warn_param) == float:
                    bw_warn_in = bw_warn_param / 100.0 * speed_in / 8
                if type(bw_crit_param) == float:
                    bw_crit_in = bw_crit_param / 100.0 * speed_in / 8
                if type(bw_warn_min_param) == float:
                    bw_warn_min_in = bw_warn_min_param / 100.0 * speed_in / 8
                if type(bw_crit_min_param) == float:
                    bw_crit_min_in = bw_crit_min_param / 100.0 * speed_in / 8
                break

            for speed_out in [ assumed_speed_out, assumed_speed_in ]:
                if not speed_out:
                    continue
                if type(bw_warn_param) == float:
                    bw_warn_out = bw_warn_param / 100.0 * speed_out / 8
                if type(bw_crit_param) == float:
                    bw_crit_out = bw_crit_param / 100.0 * speed_out / 8
                if type(bw_warn_min_param) == float:
                    bw_warn_min_out = bw_warn_min_param / 100.0 * speed_out / 8
                if type(bw_crit_min_param) == float:
                    bw_crit_min_out = bw_crit_min_param / 100.0 * speed_out / 8
                break


            # 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

            # 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 operstatus == "down":
                return state, infotext

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

                ( "out",       ifOutOctets, bw_warn_out, bw_crit_out, 0, speed_b_out),
                ( "outucast",  outucast, None, None, None, None),
                ( "outnucast", saveint(outmcast) + saveint(outbcast), None, None, 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 bw_crit != None:
                    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":
                        value = value * 8
                        return get_nic_speed_human_readable(value)
                    else:
                        return "%s/s" % get_bytes_human_readable(value)

                for what, errorrate, okrate, traffic, speed, bw_warn, bw_crit, bw_warn_min, bw_crit_min in \
                   [ ("in",  rates[4], rates[1] + rates[2], rates[0], speed_in, bw_warn_in, bw_crit_in, bw_warn_min_in, bw_crit_min_in),
                     ("out", rates[9], rates[6] + rates[7], rates[5], speed_out, bw_warn_out, bw_crit_out, bw_warn_min_out, bw_crit_min_out) ]:

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

                    if speed:
                        perc_used = 100.0 * traffic / (speed / 8)

                        assumed_info = ""
                        if assumed_speed_in or assumed_speed_out:
                            assumed_info = "/" + format_value(speed / 8)
                        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))
                        perfdata.append( ("%s_avg_%d" % (what, average), traffic_avg, bw_warn, bw_crit, 0, speed) )
                        traffic = traffic_avg # apply levels to average traffic

                    # Check bandwidth thresholds
                    if bw_crit != None and traffic >= bw_crit:
                        state = 2
                        infotext += ' (!!) >= ' + format_value(bw_crit)
                    elif bw_warn != None and traffic >= bw_warn:
                        state = max(state, 1)
                        infotext += ' (!) >= ' + format_value(bw_warn)
                    if bw_crit_min != None and traffic < bw_crit_min:
                        state = 2
                        infotext += ' (!!) < ' + format_value(bw_crit_min)
                    elif bw_warn_min != None and traffic < bw_warn_min:
                        state = max(state, 1)
                        infotext += ' (!) >= ' + format_value(bw_warn_min)

                    pacrate = okrate + errorrate
                    if pacrate > 0.0: # any packets transmitted?
                        errperc = 100.0 * errorrate / (okrate + errorrate)

                        if errperc > 0:
                            infotext += ", %s-errors: %.2f%%" % (what, errperc)

                        if err_crit != None and errperc >= err_crit:
                            state = 2
                            infotext += "(!!) >= " + str(err_crit)
                        elif err_warn != None and errperc >= err_warn:
                            state = max(state, 1)
                            infotext += "(!) >= " + str(err_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)