Playbooks to a new Lilik
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

594 lines
25 KiB

  1. # Copyright 2016 Pierre Chifflier <pollux@wzdftpd.net>
  2. #
  3. # SSH + lxc-attach connection module for Ansible 2.0
  4. #
  5. # Adapted from ansible/plugins/connection/ssh.py
  6. #
  7. # Ansible is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # Ansible is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. import fcntl
  21. import os
  22. import pipes
  23. import pty
  24. import select
  25. import shlex
  26. import subprocess
  27. from ansible import constants as C
  28. from ansible.compat.six import text_type, binary_type
  29. from ansible.plugins.connection import ConnectionBase
  30. from ansible.utils.path import unfrackpath, makedirs_safe
  31. from ansible.module_utils._text import to_bytes, to_text
  32. try:
  33. from __main__ import display
  34. except ImportError:
  35. from ansible.utils.display import Display
  36. display = Display()
  37. class Connection(ConnectionBase):
  38. transport = 'lxc_ssh'
  39. has_pipelining = True
  40. def __init__(self, play_context, new_stdin, *args, **kwargs):
  41. #print args
  42. #print kwargs
  43. super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
  44. self.host=self._play_context.remote_addr
  45. self.container_name = play_context.docker_extra_args # XXX
  46. def _connect(self):
  47. ''' connect to the lxc; nothing to do here '''
  48. display.vvv('XXX connect')
  49. super(Connection, self)._connect()
  50. #self.container_name = self.ssh._play_context.remote_addr
  51. # self._play_context.ssh_extra_args = ""
  52. #self.container = None
  53. @staticmethod
  54. def _persistence_controls(command):
  55. '''
  56. Takes a command array and scans it for ControlPersist and ControlPath
  57. settings and returns two booleans indicating whether either was found.
  58. This could be smarter, e.g. returning false if ControlPersist is 'no',
  59. but for now we do it simple way.
  60. '''
  61. controlpersist = False
  62. controlpath = False
  63. for arg in command:
  64. if 'controlpersist' in arg.lower():
  65. controlpersist = True
  66. elif 'controlpath' in arg.lower():
  67. controlpath = True
  68. return controlpersist, controlpath
  69. @staticmethod
  70. def _split_args(argstring):
  71. """
  72. Takes a string like '-o Foo=1 -o Bar="foo bar"' and returns a
  73. list ['-o', 'Foo=1', '-o', 'Bar=foo bar'] that can be added to
  74. the argument list. The list will not contain any empty elements.
  75. """
  76. return [to_text(x.strip()) for x in shlex.split(to_bytes(argstring)) if x.strip()]
  77. def _add_args(self, explanation, args):
  78. """
  79. Adds the given args to self._command and displays a caller-supplied
  80. explanation of why they were added.
  81. """
  82. self._command += args
  83. display.vvvvv('SSH: ' + explanation + ': (%s)' % ')('.join(args), host=self._play_context.remote_addr)
  84. def _build_command(self, binary, *other_args):
  85. self._command = []
  86. self._command += [binary]
  87. self._command += ['-C']
  88. if self._play_context.verbosity > 3:
  89. self._command += ['-vvv']
  90. elif binary == 'ssh':
  91. # Older versions of ssh (e.g. in RHEL 6) don't accept sftp -q.
  92. self._command += ['-q']
  93. # Next, we add [ssh_connection]ssh_args from ansible.cfg.
  94. # if self._play_context.ssh_args:
  95. # args = self._split_args(self._play_context.ssh_args)
  96. # self._add_args("ansible.cfg set ssh_args", args)
  97. # Now we add various arguments controlled by configuration file settings
  98. # (e.g. host_key_checking) or inventory variables (ansible_ssh_port) or
  99. # a combination thereof.
  100. if not C.HOST_KEY_CHECKING:
  101. self._add_args(
  102. "ANSIBLE_HOST_KEY_CHECKING/host_key_checking disabled",
  103. ("-o", "StrictHostKeyChecking=no")
  104. )
  105. if self._play_context.port is not None:
  106. self._add_args(
  107. "ANSIBLE_REMOTE_PORT/remote_port/ansible_port set",
  108. ("-o", "Port={0}".format(self._play_context.port))
  109. )
  110. key = self._play_context.private_key_file
  111. if key:
  112. self._add_args(
  113. "ANSIBLE_PRIVATE_KEY_FILE/private_key_file/ansible_ssh_private_key_file set",
  114. ("-o", "IdentityFile=\"{0}\"".format(os.path.expanduser(key)))
  115. )
  116. if not self._play_context.password:
  117. self._add_args(
  118. "ansible_password/ansible_ssh_pass not set", (
  119. "-o", "KbdInteractiveAuthentication=no",
  120. "-o", "PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey",
  121. "-o", "PasswordAuthentication=no"
  122. )
  123. )
  124. user = self._play_context.remote_user
  125. if user:
  126. self._add_args(
  127. "ANSIBLE_REMOTE_USER/remote_user/ansible_user/user/-u set",
  128. ("-o", "User={0}".format(to_bytes(self._play_context.remote_user)))
  129. )
  130. self._add_args(
  131. "ANSIBLE_TIMEOUT/timeout set",
  132. ("-o", "ConnectTimeout={0}".format(self._play_context.timeout))
  133. )
  134. # Check if ControlPersist is enabled and add a ControlPath if one hasn't
  135. # already been set.
  136. controlpersist, controlpath = self._persistence_controls(self._command)
  137. if controlpersist:
  138. self._persistent = True
  139. if not controlpath:
  140. cpdir = unfrackpath('$HOME/.ansible/cp')
  141. # The directory must exist and be writable.
  142. makedirs_safe(cpdir, 0o700)
  143. if not os.access(cpdir, os.W_OK):
  144. raise AnsibleError("Cannot write to ControlPath %s" % cpdir)
  145. args = ("-o", "ControlPath={0}".format(
  146. to_bytes(C.ANSIBLE_SSH_CONTROL_PATH % dict(directory=cpdir)))
  147. )
  148. self._add_args("found only ControlPersist; added ControlPath", args)
  149. ## Finally, we add any caller-supplied extras.
  150. if other_args:
  151. self._command += other_args
  152. return self._command
  153. def _send_initial_data(self, fh, in_data):
  154. '''
  155. Writes initial data to the stdin filehandle of the subprocess and closes
  156. it. (The handle must be closed; otherwise, for example, "sftp -b -" will
  157. just hang forever waiting for more commands.)
  158. '''
  159. display.debug('Sending initial data')
  160. try:
  161. fh.write(in_data)
  162. fh.close()
  163. except (OSError, IOError):
  164. raise AnsibleConnectionFailure('SSH Error: data could not be sent to the remote host. Make sure this host can be reached over ssh')
  165. display.debug('Sent initial data (%d bytes)' % len(in_data))
  166. # Used by _run() to kill processes on failures
  167. @staticmethod
  168. def _terminate_process(p):
  169. """ Terminate a process, ignoring errors """
  170. try:
  171. p.terminate()
  172. except (OSError, IOError):
  173. pass
  174. # This is separate from _run() because we need to do the same thing for stdout
  175. # and stderr.
  176. def _examine_output(self, source, state, chunk, sudoable):
  177. '''
  178. Takes a string, extracts complete lines from it, tests to see if they
  179. are a prompt, error message, etc., and sets appropriate flags in self.
  180. Prompt and success lines are removed.
  181. Returns the processed (i.e. possibly-edited) output and the unprocessed
  182. remainder (to be processed with the next chunk) as strings.
  183. '''
  184. output = []
  185. for l in chunk.splitlines(True):
  186. suppress_output = False
  187. #display.debug("Examining line (source=%s, state=%s): '%s'" % (source, state, l.rstrip('\r\n')))
  188. if self._play_context.prompt and self.check_password_prompt(l):
  189. display.debug("become_prompt: (source=%s, state=%s): '%s'" % (source, state, l.rstrip('\r\n')))
  190. self._flags['become_prompt'] = True
  191. suppress_output = True
  192. elif self._play_context.success_key and self.check_become_success(l):
  193. display.debug("become_success: (source=%s, state=%s): '%s'" % (source, state, l.rstrip('\r\n')))
  194. self._flags['become_success'] = True
  195. suppress_output = True
  196. elif sudoable and self.check_incorrect_password(l):
  197. display.debug("become_error: (source=%s, state=%s): '%s'" % (source, state, l.rstrip('\r\n')))
  198. self._flags['become_error'] = True
  199. elif sudoable and self.check_missing_password(l):
  200. display.debug("become_nopasswd_error: (source=%s, state=%s): '%s'" % (source, state, l.rstrip('\r\n')))
  201. self._flags['become_nopasswd_error'] = True
  202. if not suppress_output:
  203. output.append(l)
  204. # The chunk we read was most likely a series of complete lines, but just
  205. # in case the last line was incomplete (and not a prompt, which we would
  206. # have removed from the output), we retain it to be processed with the
  207. # next chunk.
  208. remainder = ''
  209. if output and not output[-1].endswith('\n'):
  210. remainder = output[-1]
  211. output = output[:-1]
  212. return ''.join(output), remainder
  213. def _run(self, cmd, in_data, sudoable=True):
  214. '''
  215. Starts the command and communicates with it until it ends.
  216. '''
  217. display_cmd = map(to_text, map(pipes.quote, cmd))
  218. display.vvv(u'SSH: EXEC {0}'.format(u' '.join(display_cmd)), host=self.host)
  219. # Start the given command. If we don't need to pipeline data, we can try
  220. # to use a pseudo-tty (ssh will have been invoked with -tt). If we are
  221. # pipelining data, or can't create a pty, we fall back to using plain
  222. # old pipes.
  223. p = None
  224. if isinstance(cmd, (text_type, binary_type)):
  225. cmd = to_bytes(cmd)
  226. else:
  227. cmd = map(to_bytes, cmd)
  228. if not in_data:
  229. try:
  230. # Make sure stdin is a proper pty to avoid tcgetattr errors
  231. master, slave = pty.openpty()
  232. p = subprocess.Popen(cmd, stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  233. stdin = os.fdopen(master, 'w', 0)
  234. os.close(slave)
  235. except (OSError, IOError):
  236. p = None
  237. if not p:
  238. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  239. stdin = p.stdin
  240. # If we are using SSH password authentication, write the password into
  241. # the pipe we opened in _build_command.
  242. if self._play_context.password:
  243. os.close(self.sshpass_pipe[0])
  244. os.write(self.sshpass_pipe[1], "{0}\n".format(to_bytes(self._play_context.password)))
  245. os.close(self.sshpass_pipe[1])
  246. ## SSH state machine
  247. #
  248. # Now we read and accumulate output from the running process until it
  249. # exits. Depending on the circumstances, we may also need to write an
  250. # escalation password and/or pipelined input to the process.
  251. states = [
  252. 'awaiting_prompt', 'awaiting_escalation', 'ready_to_send', 'awaiting_exit'
  253. ]
  254. # Are we requesting privilege escalation? Right now, we may be invoked
  255. # to execute sftp/scp with sudoable=True, but we can request escalation
  256. # only when using ssh. Otherwise we can send initial data straightaway.
  257. state = states.index('ready_to_send')
  258. if b'ssh' in cmd:
  259. if self._play_context.prompt:
  260. # We're requesting escalation with a password, so we have to
  261. # wait for a password prompt.
  262. state = states.index('awaiting_prompt')
  263. display.debug('Initial state: %s: %s' % (states[state], self._play_context.prompt))
  264. elif self._play_context.become and self._play_context.success_key:
  265. # We're requesting escalation without a password, so we have to
  266. # detect success/failure before sending any initial data.
  267. state = states.index('awaiting_escalation')
  268. display.debug('Initial state: %s: %s' % (states[state], self._play_context.success_key))
  269. # We store accumulated stdout and stderr output from the process here,
  270. # but strip any privilege escalation prompt/confirmation lines first.
  271. # Output is accumulated into tmp_*, complete lines are extracted into
  272. # an array, then checked and removed or copied to stdout or stderr. We
  273. # set any flags based on examining the output in self._flags.
  274. stdout = stderr = ''
  275. tmp_stdout = tmp_stderr = ''
  276. self._flags = dict(
  277. become_prompt=False, become_success=False,
  278. become_error=False, become_nopasswd_error=False
  279. )
  280. # select timeout should be longer than the connect timeout, otherwise
  281. # they will race each other when we can't connect, and the connect
  282. # timeout usually fails
  283. timeout = 2 + self._play_context.timeout
  284. rpipes = [p.stdout, p.stderr]
  285. for fd in rpipes:
  286. fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  287. # If we can send initial data without waiting for anything, we do so
  288. # before we call select.
  289. if states[state] == 'ready_to_send' and in_data:
  290. self._send_initial_data(stdin, in_data)
  291. state += 1
  292. while True:
  293. rfd, wfd, efd = select.select(rpipes, [], [], timeout)
  294. # We pay attention to timeouts only while negotiating a prompt.
  295. if not rfd:
  296. if state <= states.index('awaiting_escalation'):
  297. # If the process has already exited, then it's not really a
  298. # timeout; we'll let the normal error handling deal with it.
  299. if p.poll() is not None:
  300. break
  301. self._terminate_process(p)
  302. raise AnsibleError('Timeout (%ds) waiting for privilege escalation prompt: %s' % (timeout, stdout))
  303. # Read whatever output is available on stdout and stderr, and stop
  304. # listening to the pipe if it's been closed.
  305. if p.stdout in rfd:
  306. chunk = p.stdout.read()
  307. if chunk == '':
  308. rpipes.remove(p.stdout)
  309. tmp_stdout += chunk
  310. display.debug("stdout chunk (state=%s):\n>>>%s<<<\n" % (state, chunk))
  311. if p.stderr in rfd:
  312. chunk = p.stderr.read()
  313. if chunk == '':
  314. rpipes.remove(p.stderr)
  315. tmp_stderr += chunk
  316. display.debug("stderr chunk (state=%s):\n>>>%s<<<\n" % (state, chunk))
  317. # We examine the output line-by-line until we have negotiated any
  318. # privilege escalation prompt and subsequent success/error message.
  319. # Afterwards, we can accumulate output without looking at it.
  320. if state < states.index('ready_to_send'):
  321. if tmp_stdout:
  322. output, unprocessed = self._examine_output('stdout', states[state], tmp_stdout, sudoable)
  323. stdout += output
  324. tmp_stdout = unprocessed
  325. if tmp_stderr:
  326. output, unprocessed = self._examine_output('stderr', states[state], tmp_stderr, sudoable)
  327. stderr += output
  328. tmp_stderr = unprocessed
  329. else:
  330. stdout += tmp_stdout
  331. stderr += tmp_stderr
  332. tmp_stdout = tmp_stderr = ''
  333. # If we see a privilege escalation prompt, we send the password.
  334. # (If we're expecting a prompt but the escalation succeeds, we
  335. # didn't need the password and can carry on regardless.)
  336. if states[state] == 'awaiting_prompt':
  337. if self._flags['become_prompt']:
  338. display.debug('Sending become_pass in response to prompt')
  339. stdin.write('{0}\n'.format(to_bytes(self._play_context.become_pass )))
  340. self._flags['become_prompt'] = False
  341. state += 1
  342. elif self._flags['become_success']:
  343. state += 1
  344. # We've requested escalation (with or without a password), now we
  345. # wait for an error message or a successful escalation.
  346. if states[state] == 'awaiting_escalation':
  347. if self._flags['become_success']:
  348. display.debug('Escalation succeeded')
  349. self._flags['become_success'] = False
  350. state += 1
  351. elif self._flags['become_error']:
  352. display.debug('Escalation failed')
  353. self._terminate_process(p)
  354. self._flags['become_error'] = False
  355. raise AnsibleError('Incorrect %s password' % self._play_context.become_method)
  356. elif self._flags['become_nopasswd_error']:
  357. display.debug('Escalation requires password')
  358. self._terminate_process(p)
  359. self._flags['become_nopasswd_error'] = False
  360. raise AnsibleError('Missing %s password' % self._play_context.become_method)
  361. elif self._flags['become_prompt']:
  362. # This shouldn't happen, because we should see the "Sorry,
  363. # try again" message first.
  364. display.debug('Escalation prompt repeated')
  365. self._terminate_process(p)
  366. self._flags['become_prompt'] = False
  367. raise AnsibleError('Incorrect %s password' % self._play_context.become_method)
  368. # Once we're sure that the privilege escalation prompt, if any, has
  369. # been dealt with, we can send any initial data and start waiting
  370. # for output.
  371. if states[state] == 'ready_to_send':
  372. if in_data:
  373. self._send_initial_data(stdin, in_data)
  374. state += 1
  375. # Now we're awaiting_exit: has the child process exited? If it has,
  376. # and we've read all available output from it, we're done.
  377. if p.poll() is not None:
  378. if not rpipes or not rfd:
  379. break
  380. # When ssh has ControlMaster (+ControlPath/Persist) enabled, the
  381. # first connection goes into the background and we never see EOF
  382. # on stderr. If we see EOF on stdout and the process has exited,
  383. # we're probably done. We call select again with a zero timeout,
  384. # just to make certain we don't miss anything that may have been
  385. # written to stderr between the time we called select() and when
  386. # we learned that the process had finished.
  387. if p.stdout not in rpipes:
  388. timeout = 0
  389. continue
  390. # If the process has not yet exited, but we've already read EOF from
  391. # its stdout and stderr (and thus removed both from rpipes), we can
  392. # just wait for it to exit.
  393. elif not rpipes:
  394. p.wait()
  395. break
  396. # Otherwise there may still be outstanding data to read.
  397. # close stdin after process is terminated and stdout/stderr are read
  398. # completely (see also issue #848)
  399. stdin.close()
  400. if C.HOST_KEY_CHECKING:
  401. if cmd[0] == b"sshpass" and p.returncode == 6:
  402. raise AnsibleError('Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host\'s fingerprint to your known_hosts file to manage this host.')
  403. controlpersisterror = 'Bad configuration option: ControlPersist' in stderr or 'unknown configuration option: ControlPersist' in stderr
  404. if p.returncode != 0 and controlpersisterror:
  405. raise AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ssh_args in [ssh_connection] section of the config file) before running again')
  406. if p.returncode == 255 and in_data:
  407. raise AnsibleConnectionFailure('SSH Error: data could not be sent to the remote host. Make sure this host can be reached over ssh')
  408. return (p.returncode, stdout, stderr)
  409. def _exec_command(self, cmd, in_data=None, sudoable=True):
  410. ''' run a command on the remote host '''
  411. super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
  412. display.vvv(u"ESTABLISH SSH CONNECTION FOR USER: {0}".format(self._play_context.remote_user), host=self._play_context.remote_addr)
  413. # we can only use tty when we are not pipelining the modules. piping
  414. # data into /usr/bin/python inside a tty automatically invokes the
  415. # python interactive-mode but the modules are not compatible with the
  416. # interactive-mode ("unexpected indent" mainly because of empty lines)
  417. if in_data:
  418. cmd = self._build_command('ssh', self.host, cmd)
  419. else:
  420. cmd = self._build_command('ssh', '-tt', self.host, cmd)
  421. (returncode, stdout, stderr) = self._run(cmd, in_data, sudoable=sudoable)
  422. return (returncode, stdout, stderr)
  423. def dir_print(self,obj):
  424. for attr_name in dir(obj):
  425. try:
  426. attr_value = getattr(obj, attr_name)
  427. print(attr_name, attr_value, callable(attr_value))
  428. except:
  429. pass
  430. def exec_command(self, cmd, in_data=None, sudoable=False):
  431. ''' run a command on the chroot '''
  432. display.vvv('XXX exec_command: %s' % cmd)
  433. super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
  434. # print dir(self)
  435. # print dir(self._play_context)
  436. # print self._play_context._attributes
  437. # self.dir_print(self._play_context)
  438. # print dir(self._play_context._vars)
  439. # print self._play_context._attributes['vars']
  440. # vm = self._play_context.get_ds()
  441. # print( vm )
  442. # raise "blah"
  443. h = self.container_name
  444. lxc_cmd = 'lxc-attach --name %s -- /bin/sh -c %s' \
  445. % (pipes.quote(h),
  446. pipes.quote(cmd))
  447. if in_data:
  448. cmd = self._build_command('ssh', self.host, lxc_cmd)
  449. else:
  450. cmd = self._build_command('ssh', '-tt', self.host, lxc_cmd)
  451. #self.ssh.exec_command(lxc_cmd,in_data,sudoable)
  452. (returncode, stdout, stderr) = self._run(cmd, in_data, sudoable=sudoable)
  453. return (returncode, stdout, stderr)
  454. def put_file(self, in_path, out_path):
  455. ''' transfer a file from local to lxc '''
  456. display.vvv('XXX put_file %s %s' % (in_path,out_path))
  457. super(Connection, self).put_file(in_path, out_path)
  458. if not os.path.exists(in_path):
  459. raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
  460. with open(in_path,'r') as in_f:
  461. in_data = in_f.read()
  462. cmd = ('cat > %s; echo -n done' % pipes.quote(out_path))
  463. h = self.container_name
  464. lxc_cmd = 'lxc-attach --name %s -- /bin/sh -c %s' \
  465. % (pipes.quote(h),
  466. pipes.quote(cmd))
  467. if in_data:
  468. cmd = self._build_command('ssh', self.host, lxc_cmd)
  469. else:
  470. cmd = self._build_command('ssh', '-tt', self.host, lxc_cmd)
  471. #self.ssh.exec_command(lxc_cmd,in_data,sudoable)
  472. (returncode, stdout, stderr) = self._run(cmd, in_data, sudoable=False)
  473. return (returncode, stdout, stderr)
  474. def fetch_file(self, in_path, out_path):
  475. ''' fetch a file from lxc to local '''
  476. display.vvv('XXX fetch_file %s %s' % (in_path,out_path))
  477. super(Connection, self).fetch_file(in_path, out_path)
  478. cmd = ('cat %s' % pipes.quote(in_path))
  479. h = self.container_name
  480. lxc_cmd = 'lxc-attach --name %s -- /bin/sh -c %s' \
  481. % (pipes.quote(h),
  482. pipes.quote(cmd))
  483. in_data = None
  484. if in_data:
  485. cmd = self._build_command('ssh', self.host, lxc_cmd)
  486. else:
  487. cmd = self._build_command('ssh', '-tt', self.host, lxc_cmd)
  488. (returncode, stdout, stderr) = self._run(cmd, in_data, sudoable=False)
  489. if returncode != 0:
  490. raise AnsibleError("failed to transfer file from {0}:\n{1}\n{2}".format(in_path, stdout, stderr))
  491. with open(out_path,'w') as out_f:
  492. out_f.write(stdout)
  493. def close(self):
  494. ''' terminate the connection; nothing to do here '''
  495. display.vvv('XXX close')
  496. super(Connection, self).close()
  497. #self.ssh.close()
  498. self._connected = False