Exemplo n.º 1
0
    def test_remove_shebang_first_only(self):
        script = """#!/usr/bin/alabala
echo '#! switch [*]' > file
#! /usr/bin/bash
"""
        res = parser.remove_shebangs(script)
        self.assertEqual(
            res, "echo '#! switch [*]' > file\n#! /usr/bin/bash\n")
Exemplo n.º 2
0
 def test_remove_shebang(self):
     shebang = ["#!/usr/bin/alabala"]
     lines = ['line1', 'line2', 'line3']
     shebang_script = "\n".join(shebang + lines)
     res = parser.remove_shebangs(shebang_script)
     self.assertEqual(res.split("\n"), lines)
Exemplo n.º 3
0
class Processor(object):
    def __init__(self, as_user, work_dir=cloudrunner.TMP_DIR):
        self.state_manager = StateManager()
        self.as_user = as_user
        self.session_cwd = os.path.join(work_dir, uuid.uuid4().hex)
        os.makedirs(self.session_cwd)
        self.executor = Executor(as_user)

    def run(self, command, lang, env, inlines=None):
        """
        Returns ['running_user', 'cmd_status', 'std_out', 'std_err', 'env']
        """
        ret_code = -255

        if not self.executor.ready:
            yield [
                ret_code, '', '',
                'Cannot impersonate user %s\n' % self.as_user, env
            ]
            return
        mod_env = copy.copy(env)
        try:
            mod_env['HOME'] = self.executor.get_home()
            mod_env['LOGNAME'] = self.as_user
            mod_env['PWD'] = self.session_cwd
            mod_env['USER'] = self.as_user

            paths = []
            if "PYTHONPATH" in os.environ:
                paths.append(os.environ.get("PYTHONPATH"))
            paths.append(
                os.path.realpath(
                    os.path.join(
                        os.path.dirname(os.path.abspath(cloudrunner.__file__)),
                        '..')))
            paths.append(self.session_cwd)
            mod_env['PYTHONPATH'] = os.pathsep.join(paths)
            uid = self.executor.get_uid()
            gid = self.executor.get_gid()
        except Exception, ex:
            LOG.exception(ex)
            yield [
                ret_code, '',
                'Cannot impersonate user %s\n' % self.as_user, {}
            ]
            return

        for key, v in mod_env.items():
            if isinstance(v, list):
                mod_env[key] = list(stringify(*v))
            else:
                mod_env[key] = stringify1(v)
        command = parser.remove_shebangs(command.strip())

        command, suffix, mod_env = self.state_manager.set_state_handlers(
            lang, uid, gid, self.session_cwd, command, mod_env)

        inlines_str = ""
        if inlines:
            inlines_str = "\n".join(inlines)

        command = "%(comm)s %(shebang)s\n\n%(inlines)s\n%(command)s\n" % \
            dict(shebang=SHEBANG[lang if lang in SHEBANG else "bash"],
                 command=command,
                 inlines=inlines_str,
                 comm=COMMENT_SYMBOL.get(lang, '#!'))

        LOG.debug(command)
        (exec_file_fd, exec_file_name) = tempfile.mkstemp(dir=self.session_cwd,
                                                          prefix='cloudr',
                                                          suffix=suffix,
                                                          text=True)

        os.write(exec_file_fd, command)
        os.close(exec_file_fd)

        for root, dirs, files in os.walk(self.session_cwd):
            for _dir in dirs:
                dir_name = os.path.join(root, _dir)
                self.executor.chmod(dir_name, 'IR', 'IW', 'IE')
                self.executor.chown(dir_name, uid, gid)
            for _file in files:
                file_name = os.path.join(root, _file)
                self.executor.chmod(file_name, 'IR', 'IW', 'IE')
                self.executor.chown(file_name, uid, gid)

        stdout, stderr, stderr_ = ('', '', '')

        exec_file_args = self.state_manager.get_exec_commands(
            lang, exec_file_name)
        try:
            # Yield to consume streams
            popen = None
            initial_env = copy.deepcopy(mod_env)
            for k, v in initial_env.items():
                if isinstance(v, list):
                    initial_env[k] = jsonify1(v)
                else:
                    initial_env[k] = stringify1(v)
            popen = self.executor.popen(
                exec_file_args,
                self.session_cwd,
                initial_env,
                supports_shell=self.state_manager.supports_shell(lang))
            yield popen
        except OSError, oserr:
            LOG.exception(oserr)
            stderr += '%r' % oserr