/
localemod.py
269 lines (219 loc) · 7.83 KB
/
localemod.py
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
# -*- coding: utf-8 -*-
'''
Module for managing locales on POSIX-like systems.
'''
from __future__ import absolute_import
# Import python libs
import logging
import re
import os
# Import salt libs
import salt.utils
import salt.utils.locales
import salt.ext.six as six
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'locale'
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.is_windows():
return False
return __virtualname__
def _parse_localectl():
'''
Get the 'System Locale' parameters from localectl
'''
ret = {}
for line in __salt__['cmd.run']('localectl').splitlines():
cols = [x.strip() for x in line.split(':', 1)]
if len(cols) > 1:
cur_param = cols.pop(0)
if cur_param == 'System Locale':
try:
key, val = re.match('^([A-Z_]+)=(.*)$', cols[0]).groups()
except AttributeError:
log.error('Odd locale parameter "{0}" detected in localectl '
'output. This should not happen. localectl should '
'catch this. You should probably investigate what '
'caused this.'.format(cols[0]))
else:
ret[key] = val.replace('"', '')
return ret
def _localectl_get():
'''
Use systemd's localectl command to get the current locale
'''
return _parse_localectl().get('LANG', '')
def _localectl_set(locale=''):
'''
Use systemd's localectl command to set the LANG locale parameter, making
sure not to trample on other params that have been set.
'''
locale_params = _parse_localectl()
locale_params['LANG'] = str(locale)
args = ' '.join(['{0}="{1}"'.format(k, v)
for k, v in six.iteritems(locale_params)])
cmd = 'localectl set-locale {0}'.format(args)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
def list_avail():
'''
Lists available (compiled) locales
CLI Example:
.. code-block:: bash
salt '*' locale.list_avail
'''
cmd = 'locale -a'
out = __salt__['cmd.run'](cmd).split('\n')
return out
def get_locale():
'''
Get the current system locale
CLI Example:
.. code-block:: bash
salt '*' locale.get_locale
'''
cmd = ''
if 'Arch' in __grains__['os_family']:
return _localectl_get()
elif 'RedHat' in __grains__['os_family']:
cmd = 'grep "^LANG=" /etc/sysconfig/i18n'
elif 'Debian' in __grains__['os_family']:
cmd = 'grep "^LANG=" /etc/default/locale'
elif 'Gentoo' in __grains__['os_family']:
cmd = 'eselect --brief locale show'
return __salt__['cmd.run'](cmd).strip()
try:
return __salt__['cmd.run'](cmd).split('=')[1].replace('"', '')
except IndexError:
return ''
def set_locale(locale):
'''
Sets the current system locale
CLI Example:
.. code-block:: bash
salt '*' locale.set_locale 'en_US.UTF-8'
'''
if 'Arch' in __grains__['os_family']:
return _localectl_set(locale)
elif 'RedHat' in __grains__['os_family']:
if not __salt__['file.file_exists']('/etc/sysconfig/i18n'):
__salt__['file.touch']('/etc/sysconfig/i18n')
__salt__['file.replace'](
'/etc/sysconfig/i18n',
'^LANG=.*',
'LANG="{0}"'.format(locale),
append_if_not_found=True
)
elif 'Debian' in __grains__['os_family']:
update_locale = salt.utils.which('update-locale')
if update_locale is None:
raise CommandExecutionError(
'Cannot set locale: "update-locale" was not found.')
__salt__['cmd.run'](update_locale) # (re)generate /etc/default/locale
# FIXME: why are we writing to a file that is dynamically generated?
__salt__['file.replace'](
'/etc/default/locale',
'^LANG=.*',
'LANG="{0}"'.format(locale),
append_if_not_found=True
)
elif 'Gentoo' in __grains__['os_family']:
cmd = 'eselect --brief locale set {0}'.format(locale)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
return True
def avail(locale):
'''
Check if a locale is available.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' locale.avail 'en_US.UTF-8'
'''
try:
normalized_locale = salt.utils.locales.normalize_locale(locale)
except IndexError:
log.error('Unable to validate locale "{0}"'.format(locale))
return False
avail_locales = __salt__['locale.list_avail']()
locale_exists = next((True for x in avail_locales
if salt.utils.locales.normalize_locale(x.strip()) == normalized_locale), False)
return locale_exists
def gen_locale(locale, **kwargs):
'''
Generate a locale. Options:
.. versionadded:: 2014.7.0
:param locale: Any locale listed in /usr/share/i18n/locales or
/usr/share/i18n/SUPPORTED for Debian and Gentoo based distributions,
which require the charmap to be specified as part of the locale
when generating it.
verbose
Show extra warnings about errors that are normally ignored.
CLI Example:
.. code-block:: bash
salt '*' locale.gen_locale en_US.UTF-8
salt '*' locale.gen_locale 'en_IE.UTF-8 UTF-8' # Debian/Gentoo only
'''
on_debian = __grains__.get('os') == 'Debian'
on_ubuntu = __grains__.get('os') == 'Ubuntu'
on_gentoo = __grains__.get('os_family') == 'Gentoo'
on_suse = __grains__.get('os_family') == 'Suse'
locale_info = salt.utils.locales.split_locale(locale)
if on_debian or on_gentoo: # file-based search
search = '/usr/share/i18n/SUPPORTED'
valid = __salt__['file.search'](search, '^{0}$'.format(locale))
else: # directory-based search
if on_suse:
search = '/usr/share/locale'
else:
search = '/usr/share/i18n/locales'
try:
valid = "{0}_{1}".format(locale_info['language'],
locale_info['territory']) in os.listdir(search)
except OSError as ex:
log.error(ex)
raise CommandExecutionError("Locale \"{0}\" is not available.".format(locale))
if not valid:
log.error('The provided locale "{0}" is not found in {1}'.format(locale, search))
return False
if os.path.exists('/etc/locale.gen'):
__salt__['file.replace'](
'/etc/locale.gen',
r'^\s*#\s*{0}\s*$'.format(locale),
'{0}'.format(locale),
append_if_not_found=True
)
elif on_ubuntu:
__salt__['file.touch'](
'/var/lib/locales/supported.d/{0}'.format(locale_info['language'])
)
__salt__['file.replace'](
'/var/lib/locales/supported.d/{0}'.format(locale_info['language']),
locale,
locale,
append_if_not_found=True
)
if salt.utils.which("locale-gen") is not None:
cmd = ['locale-gen']
if on_gentoo:
cmd.append('--generate')
if not on_ubuntu:
cmd.append(locale)
elif salt.utils.which("localedef") is not None:
cmd = ['localedef', '--force',
'-i', "{0}_{1}".format(locale_info['language'], locale_info['territory']),
'-f', locale_info['codeset'],
locale]
cmd.append(kwargs.get('verbose', False) and '--verbose' or '--quiet')
else:
raise CommandExecutionError(
'Command "locale-gen" or "localedef" was not found on this system.')
res = __salt__['cmd.run_all'](cmd)
if res['retcode']:
log.error(res['stderr'])
if kwargs.get('verbose'):
return res
else:
return res['retcode'] == 0