| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) Ansible project |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: locale_gen |
| 11 |
short_description: Creates or removes locales |
| 12 |
description: |
| 13 |
- Manages locales in Debian and Ubuntu systems. |
| 14 |
author: |
| 15 |
- Augustus Kling (@AugustusKling) |
| 16 |
extends_documentation_fragment: |
| 17 |
- community.general._attributes |
| 18 |
attributes: |
| 19 |
check_mode: |
| 20 |
support: full |
| 21 |
diff_mode: |
| 22 |
support: none |
| 23 |
options: |
| 24 |
name: |
| 25 |
type: list |
| 26 |
elements: str |
| 27 |
description: |
| 28 |
- Name and encoding of the locales, such as V(en_GB.UTF-8). |
| 29 |
- Before community.general 9.3.0, this was a string. Using a string still works. |
| 30 |
required: true |
| 31 |
state: |
| 32 |
type: str |
| 33 |
description: |
| 34 |
- Whether the locales shall be present. |
| 35 |
choices: [absent, present] |
| 36 |
default: present |
| 37 |
|
| 38 |
notes: |
| 39 |
- Currently the module is B(only supported for Debian, Ubuntu, and Arch Linux) systems. |
| 40 |
- This module requires the package C(locales) installed in Debian and Ubuntu systems. |
| 41 |
- If C(/etc/locale.gen) exists, the module assumes to be using the B(glibc) mechanism, else it raises an error. |
| 42 |
Support for C(/var/lib/locales/supported.d/) (the V(ubuntu_legacy) mechanism) has been removed in community.general 13.0.0. |
| 43 |
- When using V(glibc) mechanism, it manages locales by editing C(/etc/locale.gen) and running C(locale-gen). |
| 44 |
- Please note that the module asserts the availability of the locale by checking the files C(/usr/share/i18n/SUPPORTED) and |
| 45 |
C(/usr/local/share/i18n/SUPPORTED), but the C(/usr/local) one is not supported by Archlinux. |
| 46 |
""" |
| 47 |
|
| 48 |
EXAMPLES = r""" |
| 49 |
- name: Ensure a locale exists |
| 50 |
community.general.locale_gen: |
| 51 |
name: de_CH.UTF-8 |
| 52 |
state: present |
| 53 |
|
| 54 |
- name: Ensure multiple locales exist |
| 55 |
community.general.locale_gen: |
| 56 |
name: |
| 57 |
- en_GB.UTF-8 |
| 58 |
- nl_NL.UTF-8 |
| 59 |
state: present |
| 60 |
""" |
| 61 |
|
| 62 |
RETURN = r""" |
| 63 |
mechanism: |
| 64 |
description: Mechanism used to deploy the locales. |
| 65 |
type: str |
| 66 |
choices: |
| 67 |
- glibc |
| 68 |
returned: success |
| 69 |
sample: glibc |
| 70 |
version_added: 10.2.0 |
| 71 |
""" |
| 72 |
|
| 73 |
import os |
| 74 |
import re |
| 75 |
|
| 76 |
from ansible_collections.community.general.plugins.module_utils._locale_gen import locale_gen_runner, locale_runner |
| 77 |
from ansible_collections.community.general.plugins.module_utils._mh.deco import check_mode_skip |
| 78 |
from ansible_collections.community.general.plugins.module_utils._module_helper import StateModuleHelper |
| 79 |
|
| 80 |
ETC_LOCALE_GEN = "/etc/locale.gen" |
| 81 |
VAR_LIB_LOCALES = "/var/lib/locales/supported.d" |
| 82 |
VAR_LIB_LOCALES_LOCAL = os.path.join(VAR_LIB_LOCALES, "local") |
| 83 |
SUPPORTED_LOCALES = ["/usr/share/i18n/SUPPORTED", "/usr/local/share/i18n/SUPPORTED"] |
| 84 |
RE_LOCALE_ENTRY = re.compile(r"^\s*#?\s*(?P<locale>\S+[\._\S]+) (?P<charset>\S+)\s*$") |
| 85 |
LOCALE_NORMALIZATION = { |
| 86 |
".utf8": ".UTF-8", |
| 87 |
".eucjp": ".EUC-JP", |
| 88 |
".iso885915": ".ISO-8859-15", |
| 89 |
".cp1251": ".CP1251", |
| 90 |
".koi8r": ".KOI8-R", |
| 91 |
".armscii8": ".ARMSCII-8", |
| 92 |
".euckr": ".EUC-KR", |
| 93 |
".gbk": ".GBK", |
| 94 |
".gb18030": ".GB18030", |
| 95 |
".euctw": ".EUC-TW", |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
class LocaleGen(StateModuleHelper): |
| 100 |
output_params = ["name"] |
| 101 |
module = dict( |
| 102 |
argument_spec=dict( |
| 103 |
name=dict(type="list", elements="str", required=True), |
| 104 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 105 |
), |
| 106 |
supports_check_mode=True, |
| 107 |
) |
| 108 |
|
| 109 |
def __init_module__(self): |
| 110 |
self.mechanisms = dict( |
| 111 |
glibc=dict( |
| 112 |
available=SUPPORTED_LOCALES, |
| 113 |
apply_change=self.apply_change_glibc, |
| 114 |
), |
| 115 |
) |
| 116 |
|
| 117 |
if os.path.exists(ETC_LOCALE_GEN): |
| 118 |
self.vars.ubuntu_mode = False |
| 119 |
self.vars.mechanism = "glibc" |
| 120 |
else: |
| 121 |
self.do_raise(f'{ETC_LOCALE_GEN} is missing. Is the package "locales" installed?') |
| 122 |
|
| 123 |
self.runner = locale_runner(self.module) |
| 124 |
|
| 125 |
self.assert_available() |
| 126 |
self.vars.set("is_present", self.is_present(), output=False) |
| 127 |
self.vars.set("state_tracking", self._state_name(self.vars.is_present), output=False, change=True) |
| 128 |
|
| 129 |
def __quit_module__(self): |
| 130 |
self.vars.state_tracking = self._state_name(self.is_present()) |
| 131 |
|
| 132 |
@staticmethod |
| 133 |
def _state_name(present): |
| 134 |
return "present" if present else "absent" |
| 135 |
|
| 136 |
def assert_available(self): |
| 137 |
"""Check if the given locales are available on the system. This is done by |
| 138 |
checking either : |
| 139 |
* if the locale is present in /etc/locales.gen |
| 140 |
* or if the locale is present in /usr/share/i18n/SUPPORTED""" |
| 141 |
|
| 142 |
self.vars.set("available_lines", [], verbosity=4) |
| 143 |
available_locale_entry_re_matches = [] |
| 144 |
for locale_path in self.mechanisms[self.vars.mechanism]["available"]: |
| 145 |
if os.path.exists(locale_path): |
| 146 |
with open(locale_path) as fd: |
| 147 |
self.vars.available_lines.extend(fd.readlines()) |
| 148 |
|
| 149 |
available_locale_entry_re_matches.extend([RE_LOCALE_ENTRY.match(line) for line in self.vars.available_lines]) |
| 150 |
|
| 151 |
locales_not_found = [] |
| 152 |
for locale in self.vars.name: |
| 153 |
# Check if the locale is not found in any of the matches |
| 154 |
if not any(match and match.group("locale") == locale for match in available_locale_entry_re_matches): |
| 155 |
locales_not_found.append(locale) |
| 156 |
|
| 157 |
# locale may be installed but not listed in the file, for example C.UTF-8 in some systems |
| 158 |
locales_not_found = self.locale_get_not_present(locales_not_found) |
| 159 |
|
| 160 |
if locales_not_found: |
| 161 |
self.do_raise( |
| 162 |
f"The following locales you have entered are not available on your system: {', '.join(locales_not_found)}" |
| 163 |
) |
| 164 |
|
| 165 |
def is_present(self): |
| 166 |
return not self.locale_get_not_present(self.vars.name) |
| 167 |
|
| 168 |
def locale_get_not_present(self, locales): |
| 169 |
runner = locale_runner(self.module) |
| 170 |
with runner() as ctx: |
| 171 |
rc, out, err = ctx.run() |
| 172 |
if self.verbosity >= 4: |
| 173 |
self.vars.locale_run_info = ctx.run_info |
| 174 |
|
| 175 |
not_found = [] |
| 176 |
for locale in locales: |
| 177 |
if not any(self.fix_case(locale) == self.fix_case(line) for line in out.splitlines()): |
| 178 |
not_found.append(locale) |
| 179 |
|
| 180 |
return not_found |
| 181 |
|
| 182 |
def fix_case(self, name): |
| 183 |
"""locale -a might return the encoding in either lower or upper case. |
| 184 |
Passing through this function makes them uniform for comparisons.""" |
| 185 |
for s, r in LOCALE_NORMALIZATION.items(): |
| 186 |
name = name.replace(s, r) |
| 187 |
return name |
| 188 |
|
| 189 |
def _get_charset_from_supported(self, locale): |
| 190 |
"""Look up the charset for a locale from the SUPPORTED files.""" |
| 191 |
for locale_path in SUPPORTED_LOCALES: |
| 192 |
if os.path.exists(locale_path): |
| 193 |
with open(locale_path) as fd: |
| 194 |
for line in fd: |
| 195 |
match = RE_LOCALE_ENTRY.match(line) |
| 196 |
if match and match.group("locale") == locale: |
| 197 |
return match.group("charset") |
| 198 |
return None |
| 199 |
|
| 200 |
def set_locale_glibc(self, names, enabled=True): |
| 201 |
"""Sets the state of the locale. Defaults to enabled.""" |
| 202 |
with open(ETC_LOCALE_GEN) as fr: |
| 203 |
lines = fr.readlines() |
| 204 |
|
| 205 |
locale_regexes = {} |
| 206 |
matched = set() |
| 207 |
|
| 208 |
for name in names: |
| 209 |
search_string = rf"^#?\s*{re.escape(name)} (?P<charset>.+)" |
| 210 |
if enabled: |
| 211 |
new_string = rf"{name} \g<charset>" |
| 212 |
else: |
| 213 |
new_string = rf"# {name} \g<charset>" |
| 214 |
locale_regexes[name] = (re.compile(search_string), new_string) |
| 215 |
|
| 216 |
def search_replace(line): |
| 217 |
for name, (search, replace) in locale_regexes.items(): |
| 218 |
new_line = search.sub(replace, line) |
| 219 |
if new_line != line: |
| 220 |
matched.add(name) |
| 221 |
line = new_line |
| 222 |
return line |
| 223 |
|
| 224 |
lines = [search_replace(line) for line in lines] |
| 225 |
|
| 226 |
# For locales not found in /etc/locale.gen (e.g. on Gentoo), add them |
| 227 |
if enabled: |
| 228 |
for name in names: |
| 229 |
if name not in matched: |
| 230 |
charset = self._get_charset_from_supported(name) |
| 231 |
if charset: |
| 232 |
lines.append(f"{name} {charset}\n") |
| 233 |
|
| 234 |
# Write the modified content back to the file |
| 235 |
with open(ETC_LOCALE_GEN, "w") as fw: |
| 236 |
fw.writelines(lines) |
| 237 |
|
| 238 |
def apply_change_glibc(self, target_state, names): |
| 239 |
"""Create or remove locale. |
| 240 |
|
| 241 |
Keyword arguments: |
| 242 |
target_state -- Desired state, either present or absent. |
| 243 |
names -- Names list including encoding such as de_CH.UTF-8. |
| 244 |
""" |
| 245 |
|
| 246 |
self.set_locale_glibc(names, enabled=(target_state == "present")) |
| 247 |
|
| 248 |
runner = locale_gen_runner(self.module) |
| 249 |
with runner() as ctx: |
| 250 |
ctx.run() |
| 251 |
|
| 252 |
@check_mode_skip |
| 253 |
def __state_fallback__(self): |
| 254 |
if self.vars.state_tracking == self.vars.state: |
| 255 |
return |
| 256 |
self.mechanisms[self.vars.mechanism]["apply_change"](self.vars.state, self.vars.name) |
| 257 |
|
| 258 |
|
| 259 |
def main(): |
| 260 |
LocaleGen.execute() |
| 261 |
|
| 262 |
|
| 263 |
if __name__ == "__main__": |
| 264 |
main() |