Refactoring: Moved check parameters from unsorted.py to dedicated modules (CMK-1393)
[check_mk.git] / cmk / utils / translations.py
blobd66cd27a34ac07f4ddc01796a45584480921cc60
1 #!/usr/bin/env python
2 # -*- encoding: utf-8; py-indent-offset: 4 -*-
3 # +------------------------------------------------------------------+
4 # | ____ _ _ __ __ _ __ |
5 # | / ___| |__ ___ ___| | __ | \/ | |/ / |
6 # | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
7 # | | |___| | | | __/ (__| < | | | | . \ |
8 # | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
9 # | |
10 # | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
11 # +------------------------------------------------------------------+
13 # This file is part of Check_MK.
14 # The official homepage is at http://mathias-kettner.de/check_mk.
16 # check_mk is free software; you can redistribute it and/or modify it
17 # under the terms of the GNU General Public License as published by
18 # the Free Software Foundation in version 2. check_mk is distributed
19 # in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
20 # out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
21 # PARTICULAR PURPOSE. See the GNU General Public License for more de-
22 # tails. You should have received a copy of the GNU General Public
23 # License along with GNU Make; see the file COPYING. If not, write
24 # to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
25 # Boston, MA 02110-1301 USA.
27 from cmk.utils.regex import regex
30 def translate_hostname(translation, hostname):
31 return _translate(translation, hostname)
34 def translate_service_description(translation, service_description):
35 if service_description.strip() in \
36 ["Check_MK", "Check_MK Agent",
37 "Check_MK Discovery", "Check_MK inventory",
38 "Check_MK HW/SW Inventory"]:
39 return service_description.strip()
40 return _translate(translation, service_description)
43 def _translate(translation, name):
44 # 1. Case conversion
45 caseconf = translation.get("case")
46 if caseconf == "upper":
47 name = name.upper()
48 elif caseconf == "lower":
49 name = name.lower()
51 # 2. Drop domain part (not applied to IP addresses!)
52 if translation.get("drop_domain") and not name[0].isdigit():
53 name = name.split(".", 1)[0]
55 # 3. Multiple regular expression conversion
56 if isinstance(translation.get("regex"), tuple):
57 translations = [translation.get("regex")]
58 else:
59 translations = translation.get("regex", [])
61 for expr, subst in translations:
62 if not expr.endswith('$'):
63 expr += '$'
64 rcomp = regex(expr)
65 # re.RegexObject.sub() by hand to handle non-existing references
66 mo = rcomp.match(name)
67 if mo:
68 name = subst
69 for nr, text in enumerate(mo.groups("")):
70 name = name.replace("\\%d" % (nr + 1), text)
71 break
73 # 4. Explicity mapping
74 for from_name, to_name in translation.get("mapping", []):
75 if from_name == name:
76 name = to_name
77 break
79 return name.strip()