Saltstack使用的cmd.run调用的是核心模块cmdmod.py,下面我们来看一下cmdmod.py模块的源码:
cat /usr/lib/python2.6/site-packages/salt/modules/cmdmod.py ...... if reset_system_locale is True: if not salt.utils.is_windows(): # Default to C! # Salt only knows how to parse English words # Don't override if the user has passed LC_ALL env.setdefault('LC_ALL', 'C') #默认设置为“C” else: # On Windows set the codepage to US English. if python_shell: cmd = 'chcp 437 > nul & ' + cmd ..... #run函数 def run(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_loglevel='debug', timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, **kwargs): ......从上可知,Salt在执行cmd.run前会将minion端的字符集默认设置为“C”,而目前大部分tomcat应用使用的是UTF-8字符集,所以Salt执行cmd.run重启tomcat后会出现日志乱码。
事实上,从早期的Salt版本,以及截至到目前最新的Salt的RPM版本2015.5.5,在执行cmd.run前都会将minion端的字符集默认设置为“C”,按照我们的思想,这是一个BUG。
解决办法:
cat /usr/lib/python2.6/site-packages/salt/modules/cmdmod.py ...... if reset_system_locale is True: if not salt.utils.is_windows(): # Default to C! # Salt only knows how to parse English words # Don't override if the user has passed LC_ALL pass else: # On Windows set the codepage to US English. if python_shell: cmd = 'chcp 437 > nul & ' + cmd ......或
cat /usr/lib/python2.6/site-packages/salt/modules/cmdmod.py ...... #run函数 def run(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_loglevel='debug', timeout=None, reset_system_locale=False, ignore_retcode=False, saltenv='base', use_vt=False, **kwargs): ......修改源码必须保证master端和minion端都被修改,后期新增minion端还要修改,十分麻烦。
如此可以考虑下面这种方法:
命令行执行:
如:
salt '10.0.10.100' cmd.run 'locale' env='{"LC_ALL": ""}' #增加参数env='{"LC_ALL": ""}'编写state.sls:
locale: cmd.run: - name: locale - env: - LC_ALL: ""
以上即可解决执行cmdmod.py修改字符集的问题。
值得庆幸的是,https://github.com/saltstack/salt上目前最新版的salt 2015.8.3已经将这个问题解决了,新的cmdmod.py源码修改如下:
...... if reset_system_locale is True: if not salt.utils.is_windows(): # Default to C! # Salt only knows how to parse English words # Don't override if the user has passed LC_ALL env.setdefault('LC_CTYPE', 'C') env.setdefault('LC_NUMERIC', 'C') env.setdefault('LC_TIME', 'C') env.setdefault('LC_COLLATE', 'C') env.setdefault('LC_MONETARY', 'C') env.setdefault('LC_MESSAGES', 'C') env.setdefault('LC_PAPER', 'C') env.setdefault('LC_NAME', 'C') env.setdefault('LC_ADDRESS', 'C') env.setdefault('LC_TELEPHONE', 'C') env.setdefault('LC_MEASUREMENT', 'C') env.setdefault('LC_IDENTIFICATION', 'C') else: # On Windows set the codepage to US English. if python_shell: cmd = 'chcp 437 > nul & ' + cmd ......仍是默认设置字符集为“C”,但是不再是”LC_ALL“为”C“