def _get_pip(module, env=None, executable=None): # Older pip only installed under the "/usr/bin/pip" name. Many Linux # distros install it there. # By default, we try to use pip required for the current python # interpreter, so people can use pip to install modules dependencies candidate_pip_basenames = ('pip2', 'pip') if PY3: # pip under python3 installs the "/usr/bin/pip3" name candidate_pip_basenames = ('pip3', ) pip = None if executable is not None: if os.path.isabs(executable): pip = executable else: # If you define your own executable that executable should be the only candidate. # As noted in the docs, executable doesn't work with virtualenvs. candidate_pip_basenames = (executable, ) elif executable is None and env is None and _have_pip_module(): # If no executable or virtualenv were specified, use the pip module for the current Python interpreter if available. # Use of `__main__` is required to support Python 2.6 since support for executing packages with `runpy` was added in Python 2.7. # Without it Python 2.6 gives the following error: pip is a package and cannot be directly executed pip = [sys.executable, '-m', 'pip.__main__'] if pip is None: if env is None: opt_dirs = [] for basename in candidate_pip_basenames: pip = module.get_bin_path(basename, False, opt_dirs) if pip is not None: break else: # For-else: Means that we did not break out of the loop # (therefore, that pip was not found) module.fail_json(msg='Unable to find any of %s to use. pip' ' needs to be installed.' % ', '.join(candidate_pip_basenames)) else: # If we're using a virtualenv we must use the pip from the # virtualenv venv_dir = os.path.join(env, 'bin') candidate_pip_basenames = (candidate_pip_basenames[0], 'pip') for basename in candidate_pip_basenames: candidate = os.path.join(venv_dir, basename) if os.path.exists(candidate) and is_executable(candidate): pip = candidate break else: # For-else: Means that we did not break out of the loop # (therefore, that pip was not found) module.fail_json( msg='Unable to find pip in the virtualenv, %s, ' % env + 'under any of these names: %s. ' % (', '.join(candidate_pip_basenames)) + 'Make sure pip is present in the virtualenv.') if not isinstance(pip, list): pip = [pip] return pip
def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.chroot = self._play_context.remote_addr if os.geteuid() != 0: raise AnsibleError("chroot connection requires running as root") # we're running as root on the local system so do some # trivial checks for ensuring 'host' is actually a chroot'able dir if not os.path.isdir(self.chroot): raise AnsibleError("%s is not a directory" % self.chroot) chrootsh = os.path.join(self.chroot, 'bin/sh') # Want to check for a usable bourne shell inside the chroot. # is_executable() == True is sufficient. For symlinks it # gets really complicated really fast. So we punt on finding that # out. As long as it's a symlink we assume that it will work if not (is_executable(chrootsh) or (os.path.lexists(chrootsh) and os.path.islink(chrootsh))): raise AnsibleError( "%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot) self.chroot_cmd = distutils.spawn.find_executable('chroot') if not self.chroot_cmd: raise AnsibleError("chroot command not found in PATH")
def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.chroot = self._play_context.remote_addr if not os.path.isdir(self.chroot): raise AnsibleError("%s is not a directory" % self.chroot) chrootsh = os.path.join(self.chroot, 'bin/sh') if not is_executable(chrootsh): raise AnsibleError("%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot)
def _get_pip(module, env=None, executable=None): # Older pip only installed under the "/usr/bin/pip" name. Many Linux # distros install it there. # By default, we try to use pip required for the current python # interpreter, so people can use pip to install modules dependencies candidate_pip_basenames = ('pip2', 'pip') if PY3: # pip under python3 installs the "/usr/bin/pip3" name candidate_pip_basenames = ('pip3', ) pip = None if executable is not None: executable = os.path.expanduser(executable) if os.path.isabs(executable): pip = executable else: # If you define your own executable that executable should be the only candidate. # As noted in the docs, executable doesn't work with virtualenvs. candidate_pip_basenames = (executable, ) if pip is None: if env is None: opt_dirs = [] for basename in candidate_pip_basenames: pip = module.get_bin_path(basename, False, opt_dirs) if pip is not None: break else: # For-else: Means that we did not break out of the loop # (therefore, that pip was not found) module.fail_json(msg='Unable to find any of %s to use. pip' ' needs to be installed.' % ', '.join(candidate_pip_basenames)) else: # If we're using a virtualenv we must use the pip from the # virtualenv venv_dir = os.path.join(env, 'bin') candidate_pip_basenames = (candidate_pip_basenames[0], 'pip') for basename in candidate_pip_basenames: candidate = os.path.join(venv_dir, basename) if os.path.exists(candidate) and is_executable(candidate): pip = candidate break else: # For-else: Means that we did not break out of the loop # (therefore, that pip was not found) module.fail_json( msg='Unable to find pip in the virtualenv,' ' %s, under any of these names: %s. Make sure pip is' ' present in the virtualenv.' % (env, ', '.join(candidate_pip_basenames))) return pip
def _get_pip(module, env=None, executable=None): # Older pip only installed under the "/usr/bin/pip" name. Many Linux # distros install it there. # By default, we try to use pip required for the current python # interpreter, so people can use pip to install modules dependencies candidate_pip_basenames = ('pip2', 'pip') if PY3: # pip under python3 installs the "/usr/bin/pip3" name candidate_pip_basenames = ('pip3',) pip = None if executable is not None: executable = os.path.expanduser(executable) if os.path.isabs(executable): pip = executable else: # If you define your own executable that executable should be the only candidate. # As noted in the docs, executable doesn't work with virtualenvs. candidate_pip_basenames = (executable,) if pip is None: if env is None: opt_dirs = [] for basename in candidate_pip_basenames: pip = module.get_bin_path(basename, False, opt_dirs) if pip is not None: break else: # For-else: Means that we did not break out of the loop # (therefore, that pip was not found) module.fail_json(msg='Unable to find any of %s to use. pip' ' needs to be installed.' % ', '.join(candidate_pip_basenames)) else: # If we're using a virtualenv we must use the pip from the # virtualenv venv_dir = os.path.join(env, 'bin') candidate_pip_basenames = (candidate_pip_basenames[0], 'pip') for basename in candidate_pip_basenames: candidate = os.path.join(venv_dir, basename) if os.path.exists(candidate) and is_executable(candidate): pip = candidate break else: # For-else: Means that we did not break out of the loop # (therefore, that pip was not found) module.fail_json(msg='Unable to find pip in the virtualenv,' ' %s, under any of these names: %s. Make sure pip is' ' present in the virtualenv.' % (env, ', '.join(candidate_pip_basenames))) return pip
def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.chroot = self._play_context.remote_addr if not os.path.isdir(self.chroot): raise AnsibleError("%s is not a directory" % self.chroot) chrootsh = os.path.join(self.chroot, 'bin/sh') if not is_executable(chrootsh): raise AnsibleError( "%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot)
def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.chroot = self._play_context.remote_addr if os.geteuid() != 0: raise AnsibleError("chroot connection requires running as root") # we're running as root on the local system so do some # trivial checks for ensuring 'host' is actually a chroot'able dir if not os.path.isdir(self.chroot): raise AnsibleError("%s is not a directory" % self.chroot) chrootsh = os.path.join(self.chroot, 'bin/sh') if not is_executable(chrootsh): raise AnsibleError("%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot) self.chroot_cmd = distutils.spawn.find_executable('chroot') if not self.chroot_cmd: raise AnsibleError("chroot command not found in PATH")
def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) osimage_name = str(self._play_context.remote_addr) self.osimage = luna.OsImage(name=osimage_name) self.path = self.osimage.get('path') self.lock = self.path + "/tmp/lchroot.lock" if os.geteuid() != 0: raise AnsibleError("lchroot connection requires running as root") # we're running as root on the local system so do some # trivial checks for ensuring 'host' is actually a chroot'able dir if not os.path.isdir(self.path): raise AnsibleError("%s is not a directory" % self.path) chrootsh = os.path.join(self.path, 'bin/sh') # Want to check for a usable bourne shell inside the chroot. # is_executable() == True is sufficient. For symlinks it # gets really complicated really fast. So we punt on finding that # out. As long as it's a symlink we assume that it will work if not (is_executable(chrootsh) or (os.path.lexists(chrootsh) and os.path.islink(chrootsh))): raise AnsibleError( "%s does not look like a chrootable dir (/bin/sh missing)" % self.path) self.chroot_cmd = distutils.spawn.find_executable('chroot') if not self.chroot_cmd: raise AnsibleError("chroot command not found in PATH") if os.path.isfile(self.lock): raise AnsibleError("%s exists. Unable to proceed." % self.lock) with open(self.lock, 'a') as f: f.write("PID %d of the ansible\n" % os.getpid()) self.prepare_mounts(self.path)
def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.chroot = self._play_context.remote_addr if os.geteuid() != 0: raise AnsibleError("chroot connection requires running as root") # we're running as root on the local system so do some # trivial checks for ensuring 'host' is actually a chroot'able dir if not os.path.isdir(self.chroot): raise AnsibleError("%s is not a directory" % self.chroot) chrootsh = os.path.join(self.chroot, 'bin/sh') # Want to check for a usable bourne shell inside the chroot. # is_executable() == True is sufficient. For symlinks it # gets really complicated really fast. So we punt on finding that # out. As long as it's a symlink we assume that it will work if not (is_executable(chrootsh) or (os.path.lexists(chrootsh) and os.path.islink(chrootsh))): raise AnsibleError("%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot) self.chroot_cmd = distutils.spawn.find_executable('chroot') if not self.chroot_cmd: raise AnsibleError("chroot command not found in PATH")
def is_executable(self, path): '''is the given path executable?''' path = self.path_dwim(path) return is_executable(path)
def main(): arg_spec = dict( name=dict(required=True), config=dict(required=False, type='path'), server_url=dict(required=False), username=dict(required=False), password=dict(required=False, no_log=True), supervisorctl_path=dict(required=False, type='path'), state=dict(required=True, choices=['present', 'started', 'restarted', 'stopped', 'absent']) ) module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=True) name = module.params['name'] is_group = False if name.endswith(':'): is_group = True name = name.rstrip(':') state = module.params['state'] config = module.params.get('config') server_url = module.params.get('server_url') username = module.params.get('username') password = module.params.get('password') supervisorctl_path = module.params.get('supervisorctl_path') # we check error message for a pattern, so we need to make sure that's in C locale module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C') if supervisorctl_path: if os.path.exists(supervisorctl_path) and is_executable(supervisorctl_path): supervisorctl_args = [supervisorctl_path] else: module.fail_json( msg="Provided path to supervisorctl does not exist or isn't executable: %s" % supervisorctl_path) else: supervisorctl_args = [module.get_bin_path('supervisorctl', True)] if config: supervisorctl_args.extend(['-c', config]) if server_url: supervisorctl_args.extend(['-s', server_url]) if username: supervisorctl_args.extend(['-u', username]) if password: supervisorctl_args.extend(['-p', password]) def run_supervisorctl(cmd, name=None, **kwargs): args = list(supervisorctl_args) # copy the master args args.append(cmd) if name: args.append(name) return module.run_command(args, **kwargs) def get_matched_processes(): matched = [] rc, out, err = run_supervisorctl('status') for line in out.splitlines(): # One status line may look like one of these two: # process not in group: # echo_date_lonely RUNNING pid 7680, uptime 13:22:18 # process in group: # echo_date_group:echo_date_00 RUNNING pid 7681, uptime 13:22:18 fields = [field for field in line.split(' ') if field != ''] process_name = fields[0] status = fields[1] if is_group: # If there is ':', this process must be in a group. if ':' in process_name: group = process_name.split(':')[0] if group != name: continue else: continue else: if process_name != name: continue matched.append((process_name, status)) return matched def take_action_on_processes(processes, status_filter, action, expected_result): to_take_action_on = [] for process_name, status in processes: if status_filter(status): to_take_action_on.append(process_name) if len(to_take_action_on) == 0: module.exit_json(changed=False, name=name, state=state) if module.check_mode: module.exit_json(changed=True) for process_name in to_take_action_on: rc, out, err = run_supervisorctl(action, process_name, check_rc=True) if '%s: %s' % (process_name, expected_result) not in out: module.fail_json(msg=out) module.exit_json(changed=True, name=name, state=state, affected=to_take_action_on) if state == 'restarted': rc, out, err = run_supervisorctl('update', check_rc=True) processes = get_matched_processes() if len(processes) == 0: module.fail_json(name=name, msg="ERROR (no such process)") take_action_on_processes(processes, lambda s: True, 'restart', 'started') processes = get_matched_processes() if state == 'absent': if len(processes) == 0: module.exit_json(changed=False, name=name, state=state) if module.check_mode: module.exit_json(changed=True) run_supervisorctl('reread', check_rc=True) rc, out, err = run_supervisorctl('remove', name) if '%s: removed process group' % name in out: module.exit_json(changed=True, name=name, state=state) else: module.fail_json(msg=out, name=name, state=state) if state == 'present': if len(processes) > 0: module.exit_json(changed=False, name=name, state=state) if module.check_mode: module.exit_json(changed=True) run_supervisorctl('reread', check_rc=True) rc, out, err = run_supervisorctl('add', name) if '%s: added process group' % name in out: module.exit_json(changed=True, name=name, state=state) else: module.fail_json(msg=out, name=name, state=state) if state == 'started': if len(processes) == 0: module.fail_json(name=name, msg="ERROR (no such process)") take_action_on_processes(processes, lambda s: s not in ('RUNNING', 'STARTING'), 'start', 'started') if state == 'stopped': if len(processes) == 0: module.fail_json(name=name, msg="ERROR (no such process)") take_action_on_processes(processes, lambda s: s in ('RUNNING', 'STARTING'), 'stop', 'stopped')
def main(): arg_spec = dict( name=dict(required=False), socket=dict(required=False, type='path'), gridinit_cmd_path=dict(required=False, type='path'), state=dict(required=True, choices=['status', 'start', 'restart', 'stop', 'reload', 'repair']) ) module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=True) name = module.params['name'] state = module.params['state'] socket = module.params.get('socket') gridinit_cmd_path = module.params.get('gridinit_cmd_path') # we check error message for a pattern, so we need to make sure that's in C locale module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C') if gridinit_cmd_path: if os.path.exists(gridinit_cmd_path) and is_executable(gridinit_cmd_path): gridinit_cmd_args = [gridinit_cmd_path] else: module.fail_json( msg="Provided path to gridinit_cmd does not exist or isn't executable: %s" % gridinit_cmd_path) else: gridinit_cmd_args = [module.get_bin_path('gridinit_cmd', True)] if socket: gridinit_cmd_args.extend(['-S', socket]) def run_gridinit_cmd(cmd, name=None, **kwargs): args = list(gridinit_cmd_args) # copy the master args args.append(cmd) if name: args.append(name) return module.run_command(args, **kwargs) def get_matched_processes(): matched = [] rc, out, err = run_gridinit_cmd('status') if name: group_name = name if re.search('@', name): group_name = name.split('@')[1] for line in out.splitlines(): # One status line may look like one of these two: # Group/Key [service] matched no service # process in group: # OPENIO-rawx-1 UP 32381 SCALAIR,rawx,rawx-1 fields = [field for field in line.split() if field != ''] # fields = [field for field in line.split() if re.search(name,line)] process_name = fields[0] print(process_name+'\n') status = fields[1] # if process_name != name: if process_name == 'KEY': continue if name: if bool(group_name in process_name) is True: matched.append((process_name, status)) break else: continue matched.append((process_name, status)) return matched def take_action_on_processes(processes, status_filter, action, expected_result): to_take_action_on = [] if action == 'reload': rc, out, err = run_gridinit_cmd(action) ret_format = out.splitlines() for line in out.splitlines(): fields = [field for field in line.split() if field != ''] status = fields[-1] subaction = fields[1] if status != 'Success': module.fail_json(name=subaction, state=status, msg="Reload failed") module.exit_json(changed=True, name=subaction, state=state, msg=ret_format) elif name is None: rc, out, err = run_gridinit_cmd(action) ret_format = out.splitlines() for line in out.splitlines(): fields = [field for field in line.split() if field != ''] process_name = fields[0] status = fields[1] if process_name == 'KEY': continue if status != 'UP': module.fail_json(name=process_name, state=status, msg="Service is not working") module.exit_json(changed=True, name=name, state=state, msg=ret_format) else: for process_name, status in processes: if status_filter(status): to_take_action_on.append(process_name) if len(to_take_action_on) == 0: module.exit_json(changed=False, name=name, state=state) if module.check_mode: module.exit_json(changed=True) for process_name in to_take_action_on: rc, out, err = run_gridinit_cmd(action, process_name, check_rc=True) ret_format = out.splitlines() module.exit_json(changed=True, name=name, state=state, affected=to_take_action_on, msg=ret_format) if state == 'restart': rc, out, err = run_gridinit_cmd('restart', check_rc=True) processes = get_matched_processes() if len(processes) == 0: module.fail_json(name=name, msg="ERROR (no such service)") take_action_on_processes(processes, lambda s: True, 'restart', 'Success') processes = get_matched_processes() if state == 'status': if len(processes) == 0: module.fail_json(name=name, msg="ERROR (no such service)") # take_action_on_processes(processes, lambda s: True, 'status', 'status') take_action_on_processes(processes, lambda s: True, 'status', 'UP') if state == 'start': if len(processes) == 0: module.fail_json(name=name, msg="ERROR (no such service)") take_action_on_processes(processes, lambda s: s not in 'UP', 'start', 'Success') if state == 'stop': if len(processes) == 0: module.fail_json(name=name, msg="ERROR (no such service)") take_action_on_processes(processes, lambda s: s not in 'DOWN', 'stop', 'Success') if state == 'reload': # if len(processes) == 0: # module.fail_json(name=name, msg="ERROR (no such service)") take_action_on_processes(processes, lambda s: True, 'reload', 'reload') if state == 'repair': if len(processes) == 0: module.fail_json(name=name, msg="ERROR (no such service)") take_action_on_processes(processes, lambda s: s in 'BROKEN', 'repair', 'repair')