2011-10-12 12:30:10 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
# 2011 Steven Armstrong (steven-cdist at armstrong.cc)
|
2013-08-28 13:39:17 +00:00
|
|
|
# 2011-2013 Nico Schottelius (nico-cdist at schottelius.org)
|
2011-10-12 12:30:10 +00:00
|
|
|
#
|
|
|
|
# This file is part of cdist.
|
|
|
|
#
|
|
|
|
# cdist 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, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# cdist is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
#
|
|
|
|
#
|
|
|
|
|
|
|
|
import io
|
|
|
|
import os
|
|
|
|
import sys
|
2014-01-08 22:53:08 +00:00
|
|
|
import glob
|
2011-10-12 12:30:10 +00:00
|
|
|
import subprocess
|
|
|
|
import logging
|
2016-08-12 19:14:56 +00:00
|
|
|
import multiprocessing
|
2011-10-12 12:30:10 +00:00
|
|
|
|
|
|
|
import cdist
|
2016-08-12 19:14:56 +00:00
|
|
|
import cdist.exec.util as exec_util
|
2016-12-03 17:12:38 +00:00
|
|
|
import cdist.util.ipaddr as ipaddr
|
2016-12-08 20:48:59 +00:00
|
|
|
from cdist.mputil import mp_pool_run
|
2016-11-02 12:35:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _wrap_addr(addr):
|
|
|
|
"""If addr is IPv6 then return addr wrapped between '[' and ']',
|
|
|
|
otherwise return it intact."""
|
2016-12-03 17:12:38 +00:00
|
|
|
if ipaddr.is_ipv6(addr):
|
2016-11-02 12:35:48 +00:00
|
|
|
return "".join(("[", addr, "]", ))
|
|
|
|
else:
|
|
|
|
return addr
|
|
|
|
|
|
|
|
|
2011-10-14 23:11:54 +00:00
|
|
|
class DecodeError(cdist.Error):
|
|
|
|
def __init__(self, command):
|
|
|
|
self.command = command
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return "Cannot decode output of " + " ".join(self.command)
|
|
|
|
|
2011-10-12 12:30:10 +00:00
|
|
|
|
|
|
|
class Remote(object):
|
|
|
|
"""Execute commands remotely.
|
|
|
|
|
|
|
|
All interaction with the remote side should be done through this class.
|
|
|
|
Directly accessing the remote side from python code is a bug.
|
|
|
|
|
|
|
|
"""
|
2013-08-19 09:33:44 +00:00
|
|
|
def __init__(self,
|
|
|
|
target_host,
|
|
|
|
remote_exec,
|
|
|
|
remote_copy,
|
2017-06-29 08:18:46 +00:00
|
|
|
base_path=None,
|
2017-08-04 10:51:03 +00:00
|
|
|
quiet_mode=None,
|
|
|
|
archiving_mode=None):
|
2011-10-12 12:30:10 +00:00
|
|
|
self.target_host = target_host
|
|
|
|
self._exec = remote_exec
|
|
|
|
self._copy = remote_copy
|
|
|
|
|
2013-08-19 09:33:44 +00:00
|
|
|
if base_path:
|
|
|
|
self.base_path = base_path
|
|
|
|
else:
|
|
|
|
self.base_path = "/var/lib/cdist"
|
2017-06-29 08:18:46 +00:00
|
|
|
self.quiet_mode = quiet_mode
|
2017-08-04 10:51:03 +00:00
|
|
|
self.archiving_mode = archiving_mode
|
2013-08-19 09:33:44 +00:00
|
|
|
|
2011-10-12 12:30:10 +00:00
|
|
|
self.conf_path = os.path.join(self.base_path, "conf")
|
|
|
|
self.object_path = os.path.join(self.base_path, "object")
|
|
|
|
|
|
|
|
self.type_path = os.path.join(self.conf_path, "type")
|
|
|
|
self.global_explorer_path = os.path.join(self.conf_path, "explorer")
|
|
|
|
|
2016-08-12 19:14:56 +00:00
|
|
|
self._open_logger()
|
2011-10-18 11:32:36 +00:00
|
|
|
|
2013-08-18 22:36:25 +00:00
|
|
|
self._init_env()
|
|
|
|
|
2016-08-12 19:14:56 +00:00
|
|
|
def _open_logger(self):
|
2016-08-14 20:27:39 +00:00
|
|
|
self.log = logging.getLogger(self.target_host[0])
|
2016-08-12 19:14:56 +00:00
|
|
|
|
|
|
|
# logger is not pickable, so remove it when we pickle
|
|
|
|
def __getstate__(self):
|
|
|
|
state = self.__dict__.copy()
|
|
|
|
if 'log' in state:
|
|
|
|
del state['log']
|
|
|
|
return state
|
|
|
|
|
|
|
|
# recreate logger when we unpickle
|
|
|
|
def __setstate__(self, state):
|
|
|
|
self.__dict__.update(state)
|
|
|
|
self._open_logger()
|
|
|
|
|
2013-08-18 22:36:25 +00:00
|
|
|
def _init_env(self):
|
2013-08-18 23:38:28 +00:00
|
|
|
"""Setup environment for scripts - HERE????"""
|
|
|
|
# FIXME: better do so in exec functions that require it!
|
|
|
|
os.environ['__remote_copy'] = self._copy
|
|
|
|
os.environ['__remote_exec'] = self._exec
|
2013-08-18 22:36:25 +00:00
|
|
|
|
2012-10-30 15:07:00 +00:00
|
|
|
def create_files_dirs(self):
|
2011-10-12 12:30:10 +00:00
|
|
|
self.rmdir(self.base_path)
|
|
|
|
self.mkdir(self.base_path)
|
2013-04-08 17:57:28 +00:00
|
|
|
self.run(["chmod", "0700", self.base_path])
|
2011-10-12 12:30:10 +00:00
|
|
|
self.mkdir(self.conf_path)
|
|
|
|
|
2017-08-04 10:51:03 +00:00
|
|
|
def rmfile(self, path):
|
|
|
|
"""Remove file on the remote side."""
|
|
|
|
self.log.trace("Remote rm: %s", path)
|
|
|
|
self.run(["rm", "-f", path])
|
|
|
|
|
2011-10-12 12:30:10 +00:00
|
|
|
def rmdir(self, path):
|
|
|
|
"""Remove directory on the remote side."""
|
2017-06-28 21:36:42 +00:00
|
|
|
self.log.trace("Remote rmdir: %s", path)
|
2011-10-12 12:30:10 +00:00
|
|
|
self.run(["rm", "-rf", path])
|
|
|
|
|
|
|
|
def mkdir(self, path):
|
|
|
|
"""Create directory on the remote side."""
|
2017-06-28 21:36:42 +00:00
|
|
|
self.log.trace("Remote mkdir: %s", path)
|
2011-10-12 12:30:10 +00:00
|
|
|
self.run(["mkdir", "-p", path])
|
|
|
|
|
2017-08-04 10:51:03 +00:00
|
|
|
def extract_archive(self, path, mode):
|
|
|
|
"""Extract archive path on the remote side."""
|
|
|
|
import cdist.autil as autil
|
|
|
|
|
|
|
|
self.log.trace("Remote extract archive: %s", path)
|
|
|
|
command = ["tar", "-x", "-m", "-C", ]
|
|
|
|
directory = os.path.dirname(path)
|
|
|
|
command.append(directory)
|
|
|
|
xopt = autil.get_extract_option(mode)
|
|
|
|
if xopt:
|
|
|
|
command.append(xopt)
|
|
|
|
command.append("-f")
|
|
|
|
command.append(path)
|
|
|
|
self.run(command)
|
|
|
|
|
|
|
|
def _transfer_file(self, source, destination):
|
|
|
|
command = self._copy.split()
|
|
|
|
command.extend([source, '{0}:{1}'.format(
|
|
|
|
_wrap_addr(self.target_host[0]), destination)])
|
|
|
|
self._run_command(command)
|
|
|
|
|
2016-12-04 19:27:42 +00:00
|
|
|
def transfer(self, source, destination, jobs=None):
|
2011-10-12 12:30:10 +00:00
|
|
|
"""Transfer a file or directory to the remote side."""
|
2017-06-28 21:36:42 +00:00
|
|
|
self.log.trace("Remote transfer: %s -> %s", source, destination)
|
2017-07-14 19:47:30 +00:00
|
|
|
# self.rmdir(destination)
|
2014-01-08 22:53:08 +00:00
|
|
|
if os.path.isdir(source):
|
|
|
|
self.mkdir(destination)
|
2017-08-04 10:51:03 +00:00
|
|
|
used_archiving = False
|
|
|
|
if self.archiving_mode:
|
|
|
|
self.log.trace("Remote transfer in archiving mode")
|
|
|
|
import cdist.autil as autil
|
|
|
|
|
|
|
|
# create archive
|
|
|
|
tarpath, fcnt = autil.tar(source, self.archiving_mode)
|
|
|
|
if tarpath is None:
|
|
|
|
self.log.trace(("Files count {} is lower than {} limit, "
|
|
|
|
"skipping archiving").format(
|
|
|
|
fcnt, autil.FILES_LIMIT))
|
|
|
|
else:
|
|
|
|
self.log.trace(("Archiving mode, tarpath: %s, file count: "
|
|
|
|
"%s"), tarpath, fcnt)
|
|
|
|
# get archive name
|
|
|
|
tarname = os.path.basename(tarpath)
|
|
|
|
self.log.trace("Archiving mode tarname: %s", tarname)
|
|
|
|
# archive path at the remote
|
|
|
|
desttarpath = os.path.join(destination, tarname)
|
|
|
|
self.log.trace(
|
|
|
|
"Archiving mode desttarpath: %s", desttarpath)
|
|
|
|
# transfer archive to the remote side
|
|
|
|
self.log.trace("Archiving mode: transfering")
|
|
|
|
self._transfer_file(tarpath, desttarpath)
|
|
|
|
# extract archive at the remote
|
|
|
|
self.log.trace("Archiving mode: extracting")
|
|
|
|
self.extract_archive(desttarpath, self.archiving_mode)
|
|
|
|
# remove remote archive
|
|
|
|
self.log.trace("Archiving mode: removing remote archive")
|
|
|
|
self.rmfile(desttarpath)
|
|
|
|
# remove local archive
|
|
|
|
self.log.trace("Archiving mode: removing local archive")
|
|
|
|
os.remove(tarpath)
|
|
|
|
used_archiving = True
|
|
|
|
if not used_archiving:
|
|
|
|
if jobs:
|
|
|
|
self._transfer_dir_parallel(source, destination, jobs)
|
|
|
|
else:
|
|
|
|
self._transfer_dir_sequential(source, destination)
|
2016-12-04 19:27:42 +00:00
|
|
|
elif jobs:
|
|
|
|
raise cdist.Error("Source {} is not a directory".format(source))
|
2014-01-08 22:53:08 +00:00
|
|
|
else:
|
2017-08-04 10:51:03 +00:00
|
|
|
self._transfer_file(source, destination)
|
2011-10-12 12:30:10 +00:00
|
|
|
|
2017-07-27 07:49:06 +00:00
|
|
|
def _transfer_dir_commands(self, source, destination):
|
2016-12-04 19:27:42 +00:00
|
|
|
for f in glob.glob1(source, '*'):
|
|
|
|
command = self._copy.split()
|
|
|
|
path = os.path.join(source, f)
|
|
|
|
command.extend([path, '{0}:{1}'.format(
|
|
|
|
_wrap_addr(self.target_host[0]), destination)])
|
2017-07-27 07:49:06 +00:00
|
|
|
yield command
|
|
|
|
|
|
|
|
def _transfer_dir_sequential(self, source, destination):
|
2017-07-27 07:51:23 +00:00
|
|
|
for command in self._transfer_dir_commands(source, destination):
|
2016-12-04 19:27:42 +00:00
|
|
|
self._run_command(command)
|
|
|
|
|
|
|
|
def _transfer_dir_parallel(self, source, destination, jobs):
|
2016-08-12 19:14:56 +00:00
|
|
|
"""Transfer a directory to the remote side in parallel mode."""
|
2017-06-28 21:36:42 +00:00
|
|
|
self.log.debug("Remote transfer in {} parallel jobs".format(
|
2016-12-04 19:27:42 +00:00
|
|
|
jobs))
|
2017-06-28 21:36:42 +00:00
|
|
|
self.log.trace("Multiprocessing start method is {}".format(
|
2016-12-04 19:27:42 +00:00
|
|
|
multiprocessing.get_start_method()))
|
2017-06-28 21:36:42 +00:00
|
|
|
self.log.trace(("Starting multiprocessing Pool for parallel "
|
2016-12-04 19:27:42 +00:00
|
|
|
"remote transfer"))
|
2017-07-27 07:51:23 +00:00
|
|
|
args = [
|
|
|
|
(command, )
|
|
|
|
for command in self._transfer_dir_commands(source, destination)
|
|
|
|
]
|
2017-07-27 07:49:06 +00:00
|
|
|
if len(args) == 1:
|
|
|
|
self.log.debug("Only one dir entry, transfering sequentially")
|
|
|
|
self._run_command(args[0])
|
|
|
|
else:
|
|
|
|
mp_pool_run(self._run_command, args, jobs=jobs)
|
2017-06-28 21:36:42 +00:00
|
|
|
self.log.trace(("Multiprocessing for parallel transfer "
|
2016-12-08 20:48:59 +00:00
|
|
|
"finished"))
|
2016-08-12 19:14:56 +00:00
|
|
|
|
2012-02-15 16:01:03 +00:00
|
|
|
def run_script(self, script, env=None, return_output=False):
|
|
|
|
"""Run the given script with the given environment on the remote side.
|
|
|
|
Return the output as a string.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2016-07-05 18:44:24 +00:00
|
|
|
command = [os.environ.get('CDIST_REMOTE_SHELL', "/bin/sh"), "-e"]
|
2012-02-15 16:01:03 +00:00
|
|
|
command.append(script)
|
|
|
|
|
|
|
|
return self.run(command, env, return_output)
|
|
|
|
|
2011-10-14 13:52:16 +00:00
|
|
|
def run(self, command, env=None, return_output=False):
|
2011-10-12 12:30:10 +00:00
|
|
|
"""Run the given command with the given environment on the remote side.
|
|
|
|
Return the output as a string.
|
|
|
|
|
|
|
|
"""
|
|
|
|
# prefix given command with remote_exec
|
|
|
|
cmd = self._exec.split()
|
2016-08-10 21:56:56 +00:00
|
|
|
cmd.append(self.target_host[0])
|
2012-02-15 16:01:03 +00:00
|
|
|
|
|
|
|
# can't pass environment to remote side, so prepend command with
|
|
|
|
# variable declarations
|
|
|
|
|
2016-03-18 20:57:50 +00:00
|
|
|
# cdist command prepended with variable assignments expects
|
|
|
|
# posix shell (bourne, bash) at the remote as user default shell.
|
|
|
|
# If remote user shell isn't poxis shell, but for e.g. csh/tcsh
|
|
|
|
# then these var assignments are not var assignments for this
|
|
|
|
# remote shell, it tries to execute it as a command and fails.
|
|
|
|
# So really do this by default:
|
|
|
|
# /bin/sh -c 'export <var assignments>; command'
|
|
|
|
# so that constructed remote command isn't dependent on remote
|
|
|
|
# shell. Do this only if env is not None. env breaks this.
|
|
|
|
# Explicitly use /bin/sh, because var assignments assume poxis
|
|
|
|
# shell already.
|
|
|
|
# This leaves the posibility to write script that needs to be run
|
|
|
|
# remotely in e.g. csh and setting up CDIST_REMOTE_SHELL to e.g.
|
|
|
|
# /bin/csh will execute this script in the right way.
|
|
|
|
if env:
|
|
|
|
remote_env = [" export %s=%s;" % item for item in env.items()]
|
2016-07-05 18:44:24 +00:00
|
|
|
string_cmd = ("/bin/sh -c '" + " ".join(remote_env) +
|
|
|
|
" ".join(command) + "'")
|
2016-03-18 20:57:50 +00:00
|
|
|
cmd.append(string_cmd)
|
|
|
|
else:
|
|
|
|
cmd.extend(command)
|
2011-11-18 13:40:25 +00:00
|
|
|
return self._run_command(cmd, env=env, return_output=return_output)
|
2011-10-12 12:30:10 +00:00
|
|
|
|
2011-11-18 13:40:25 +00:00
|
|
|
def _run_command(self, command, env=None, return_output=False):
|
2011-10-12 12:30:10 +00:00
|
|
|
"""Run the given command with the given environment.
|
|
|
|
Return the output as a string.
|
|
|
|
|
|
|
|
"""
|
2016-07-05 18:44:24 +00:00
|
|
|
assert isinstance(command, (list, tuple)), (
|
|
|
|
"list or tuple argument expected, got: %s" % command)
|
2011-10-18 11:32:36 +00:00
|
|
|
|
2016-08-10 21:56:56 +00:00
|
|
|
# export target_host, target_hostname, target_fqdn
|
|
|
|
# for use in __remote_{exec,copy} scripts
|
2011-10-21 13:17:19 +00:00
|
|
|
os_environ = os.environ.copy()
|
2016-08-10 21:56:56 +00:00
|
|
|
os_environ['__target_host'] = self.target_host[0]
|
|
|
|
os_environ['__target_hostname'] = self.target_host[1]
|
|
|
|
os_environ['__target_fqdn'] = self.target_host[2]
|
2011-10-21 13:17:19 +00:00
|
|
|
|
2017-06-28 21:36:42 +00:00
|
|
|
self.log.trace("Remote run: %s", command)
|
2011-10-12 12:30:10 +00:00
|
|
|
try:
|
2017-06-29 08:18:46 +00:00
|
|
|
if self.quiet_mode:
|
|
|
|
stderr = subprocess.DEVNULL
|
|
|
|
else:
|
|
|
|
stderr = None
|
|
|
|
output, errout = exec_util.call_get_output(
|
|
|
|
command, env=os_environ, stderr=stderr)
|
2017-06-28 21:36:42 +00:00
|
|
|
self.log.trace("Remote stdout: {}".format(output))
|
2016-07-15 06:22:05 +00:00
|
|
|
# Currently, stderr is not captured.
|
2017-06-28 21:36:42 +00:00
|
|
|
# self.log.trace("Remote stderr: {}".format(errout))
|
2011-10-14 13:52:16 +00:00
|
|
|
if return_output:
|
2016-06-03 10:20:28 +00:00
|
|
|
return output.decode()
|
|
|
|
except subprocess.CalledProcessError as e:
|
2016-06-24 09:18:24 +00:00
|
|
|
exec_util.handle_called_process_error(e, command)
|
2011-10-12 12:30:10 +00:00
|
|
|
except OSError as error:
|
2013-08-19 09:45:43 +00:00
|
|
|
raise cdist.Error(" ".join(command) + ": " + error.args[1])
|
2011-10-14 23:11:54 +00:00
|
|
|
except UnicodeDecodeError:
|
|
|
|
raise DecodeError(command)
|