def run(self): """Exec into the tree.""" s6_envdir = subproc.resolve('s6_envdir') utils.sane_execvp(s6_envdir, [ s6_envdir, self.paths.env_dir, subproc.resolve('s6_svscan'), self.paths.svscan_tree_dir ])
def run_putty(host, port, sshcmd, command): """Runs plink/putty (windows).""" if not host or not port: return -2 # Trick putty into storing ssh key automatically. plink = os.path.join(os.path.dirname(sshcmd), 'plink.exe') if not shutil.which(plink): cli.bad_exit('{} cannot be found in the PATH'.format(plink)) store_key_cmd = [ plink, '-P', port, '%s@%s' % (os.environ['USERNAME'], host), 'exit' ] _LOGGER.debug('Importing host key: %s', store_key_cmd) store_key_proc = subprocess.Popen(store_key_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) out, err = store_key_proc.communicate(input='y\n\n\n\n\n\n\n\n\n'.encode()) _LOGGER.debug('plink STDOUT: %s', out) _LOGGER.debug('plink STDERR: %s', err) if command: sshcmd = plink ssh = [sshcmd, '-P', port, '%s@%s' % (os.environ['USERNAME'], host)] if command: ssh.extend(command) devnull = {} def _get_devnull(): """Gets handle to the null device.""" if not devnull: devnull['fd'] = os.open(os.devnull, os.O_RDWR) return devnull['fd'] if not shutil.which(sshcmd): cli.bad_exit('{} cannot be found in the PATH'.format(sshcmd)) _LOGGER.debug('Starting ssh: %s', ssh) try: if os.path.basename(sshcmd).lower() == 'putty.exe': utils.sane_execvp(ssh[0], ssh) else: # Call plink. Redirect to devnull if std streams are empty/invalid. subprocess.call( ssh, stdin=None if _check_handle(sys.stdin) else _get_devnull(), stdout=None if _check_handle(sys.stdout) else _get_devnull(), stderr=None if _check_handle(sys.stderr) else _get_devnull()) except KeyboardInterrupt: sys.exit(0) finally: if devnull: os.close(devnull['fd'])
def _run(script): """Runs the services. """ if os.name == 'nt': sys.exit(subprocess.call(script)) else: utils.sane_execvp(script, [script])
def exec_pid1(cmd, ipc=True, mount=True, proc=True, close_fds=True, restore_signals=True, propagation=None): """Exec command line under pid1. """ pid1 = resolve('pid1') safe_cmd = _alias_command(cmd) args = [pid1] if ipc: args.append('-i') if mount: args.append('-m') if proc: args.append('-p') if propagation is not None: args.append('--propagation') args.append(propagation) args.extend(safe_cmd) _LOGGER.debug('exec_pid1: %r', args) utils.sane_execvp(args[0], args, close_fds=close_fds, signals=restore_signals)
def invoke(self, ctx): """ invoke the command in a subprocess if it is executable otherwise use it in process """ name = ctx.protected_args[0] try: module = plugin_manager.load(module_name, name) except KeyError: return super(MCommand, self).invoke(ctx) module_path = module.__file__ if module_path.endswith('pyc'): module_path = module_path[:-1] # shebang doesn't work on windows # we use .cmd or a hardcoded default interpreter if os.name == 'nt': nt_path = module_path[:-2] + 'cmd' if os.path.exists(nt_path): utils.sane_execvp(nt_path, [nt_path] + ctx.args) else: _LOGGER.critical( "%s cli is not supported on windows", name) else: is_exec = os.access(module_path, os.X_OK) if not is_exec: return super(MCommand, self).invoke(ctx) utils.sane_execvp(module_path, [os.path.basename(module_path)] + ctx.args)
def safe_exec(cmd, close_fds=True, restore_signals=True): """Exec command line using os.execvp. """ safe_cmd = _alias_command(cmd) _LOGGER.debug('safe_exec: %r', safe_cmd) utils.sane_execvp(safe_cmd[0], safe_cmd, close_fds=close_fds, signals=restore_signals)
def exec_fghack(cmd, close_fds=True, restore_signals=True): """Anti-backgrounding exec command. """ fghack = resolve('s6_fghack') safe_cmd = _alias_command(cmd) args = [fghack] + safe_cmd _LOGGER.debug('exec_fghack: %r', args) utils.sane_execvp(args[0], args, close_fds=close_fds, signals=restore_signals)
def run_unix(host, port, ssh, command): """Runs standard ssh (non-windows).""" if not host or not port: return -2 ssh = [ ssh, '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no', '-p', port, host ] + command _LOGGER.debug('Starting ssh: %s', ssh) utils.sane_execvp(ssh[0], ssh)
def test_sane_execvp(self): """Tests sane execvp wrapper. """ # do not complain about accessing protected member _SIGNALS # pylint: disable=W0212 utils.sane_execvp('/bin/sleep', ['sleep', '30']) if six.PY2: utils.closefrom.assert_called_with(3) signal.signal.assert_has_calls( [mock.call(i, signal.SIG_DFL) for i in utils._SIGNALS]) os.execvp.assert_called_with('/bin/sleep', ['sleep', '30'])
def run_unix(host, port, ssh, command): """Runs standard ssh (non-windows).""" if not host or not port: return -2 if not utils.which(ssh): cli.bad_exit('{} cannot be found in the PATH'.format(ssh)) ssh = [ssh, '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no', '-p', port, host] + command _LOGGER.debug('Starting ssh: %s', ssh) utils.sane_execvp(ssh[0], ssh)
def cgexec(into, subcommand): """execs command into given cgroup(s). """ cgrps = [cgrp.split(':') for cgrp in into] for (subsystem, path) in cgrps: pathplus = path.split('=') if len(pathplus) == 2: group = os.path.dirname(pathplus[0]) pseudofile = os.path.basename(pathplus[0]) value = pathplus[1] cgroups.set_value(subsystem, group, pseudofile, value) else: cgutils.create(subsystem, path) cgroups.join(subsystem, path) if subcommand: execargs = list(subcommand) utils.sane_execvp(execargs[0], execargs)
def run_putty(host, port, sshcmd, command): """Runs standard ssh (non-windows).""" if not host or not port: return -2 # Trick putty into storing ssh key automatically. plink = os.path.join(os.path.dirname(sshcmd), 'plink.exe') store_key_cmd = [ plink, '-P', port, '%s@%s' % (os.environ['USERNAME'], host), 'exit' ] _LOGGER.debug('Importing host key: %s', store_key_cmd) store_key_proc = subprocess.Popen(store_key_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) out, err = store_key_proc.communicate(input='y\n\n\n\n\n\n\n\n\n'.encode()) _LOGGER.debug('plink STDOUT: %s', out) _LOGGER.debug('plink STDERR: %s', err) if command: sshcmd = plink ssh = [sshcmd, '-P', port, '%s@%s' % (os.environ['USERNAME'], host)] if command: ssh.extend(command) _LOGGER.debug('Starting ssh: %s', ssh) try: if os.path.basename(sshcmd).tolower() == 'putty.exe': utils.sane_execvp(ssh[0], ssh) else: subprocess.call(ssh) except KeyboardInterrupt: sys.exit(0) return -1
def reboot_monitor(command): """Runs node reboot monitor.""" reboot_cmd = list(command) _LOGGER.info('Initializing reboot monitor: %r', reboot_cmd) zkclient = context.GLOBAL.zk.conn zkclient.add_listener(zkutils.exit_on_lost) while not zkclient.exists(z.REBOOTS): _LOGGER.warning('%r node not created yet. Cell masters running?', z.REBOOTS) time.sleep(30) hostname = sysinfo.hostname() up_since = sysinfo.up_since() _LOGGER.info('Server: %s, up since: %s', hostname, up_since) reboot_path = z.path.reboot(hostname) reboot_trigger = zkclient.handler.event_object() reboot_trigger.clear() @zkclient.DataWatch(reboot_path) @utils.exit_on_unhandled def _watch_reboot(data, stat, event): """Watch reboot node.""" if data is None and event is None: _LOGGER.info('Reboot node does not exist, ignore.') return True elif event is not None and event.type == 'DELETED': _LOGGER.info('Reboot Node deleted, ignore.') return True # We have a reboot request node if stat.created > up_since: _LOGGER.info('Reboot requested at: %s, up since: %s', time.ctime(stat.created), time.ctime(up_since)) reboot_trigger.set() else: _LOGGER.info('Reboot success, requested at %s, up since: %s', time.ctime(stat.created), time.ctime(up_since)) _LOGGER.info('Deleting zknode: %r', reboot_path) zkutils.ensure_deleted(zkclient, reboot_path) return True # We now wait for the reboot trigger reboot_trigger.wait() # Actual reboot procedure below _LOGGER.info('service shutdown.') # Strictly speaking this is not enough for graceful shutdown. # # We need a proper shutdown procedure developed. _LOGGER.info('Checking blackout list.') zk_blackout_path = z.path.blackedout_server(hostname) while zkclient.exists(zk_blackout_path): _LOGGER.info('Node blacked out - will wait.') time.sleep(60) if time.time() - up_since > _MIN_UPTIME_BEFORE_REBOOT: _LOGGER.info('exec: %r', reboot_cmd) utils.sane_execvp(reboot_cmd[0], reboot_cmd) else: _LOGGER.info('Possible reboot loop detected, blackout the node.') zkutils.ensure_exists( zkclient, zk_blackout_path, acl=[zkclient.make_host_acl(hostname, 'rwcda')], data='Possible reboot loop detected.')
def exec_cmd(cmd): """Exec command line in treadmill environment.""" args = list(cmd) _LOGGER.info('execvp: %s, %r', args[0], args) utils.sane_execvp(args[0], args)
def safe_exec(cmd): """Exec command line using os.execvp.""" safe_cmd = _alias_command(cmd) _LOGGER.debug('safe_exec: %r', safe_cmd) utils.sane_execvp(safe_cmd[0], safe_cmd)