def _get_pack_common_libs_path(self, pack_ref): """ Retrieve path to the pack common lib/ directory taking git work tree path into account (if used). """ worktree_path = self.git_worktree_path pack_common_libs_path = get_pack_common_libs_path_for_pack_ref(pack_ref=pack_ref) if not worktree_path: return pack_common_libs_path # Modify the path so it uses git worktree directory pack_base_path = get_pack_base_path(pack_name=pack_ref) new_pack_common_libs_path = pack_common_libs_path.replace(pack_base_path, '') # Remove leading slash (if any) if new_pack_common_libs_path.startswith('/'): new_pack_common_libs_path = new_pack_common_libs_path[1:] new_pack_common_libs_path = os.path.join(worktree_path, new_pack_common_libs_path) # Check to prevent directory traversal common_prefix = os.path.commonprefix([worktree_path, new_pack_common_libs_path]) if common_prefix != worktree_path: raise ValueError('pack libs path is not located inside the pack directory') return new_pack_common_libs_path
def _spawn_sensor_process(self, sensor): """ Spawn a new process for the provided sensor. New process uses isolated Python binary from a virtual environment belonging to the sensor pack. """ sensor_id = self._get_sensor_id(sensor=sensor) pack_ref = sensor['pack'] virtualenv_path = get_sandbox_virtualenv_path(pack=pack_ref) python_path = get_sandbox_python_binary_path(pack=pack_ref) if virtualenv_path and not os.path.isdir(virtualenv_path): format_values = {'pack': sensor['pack'], 'virtualenv_path': virtualenv_path} msg = PACK_VIRTUALENV_DOESNT_EXIST % format_values raise Exception(msg) trigger_type_refs = sensor['trigger_types'] or [] trigger_type_refs = ','.join(trigger_type_refs) parent_args = json.dumps(sys.argv[1:]) args = [ python_path, WRAPPER_SCRIPT_PATH, '--pack=%s' % (sensor['pack']), '--file-path=%s' % (sensor['file_path']), '--class-name=%s' % (sensor['class_name']), '--trigger-type-refs=%s' % (trigger_type_refs), '--parent-args=%s' % (parent_args) ] if sensor['poll_interval']: args.append('--poll-interval=%s' % (sensor['poll_interval'])) sandbox_python_path = get_sandbox_python_path(inherit_from_parent=True, inherit_parent_virtualenv=True) if self._enable_common_pack_libs: pack_common_libs_path = get_pack_common_libs_path_for_pack_ref(pack_ref=pack_ref) else: pack_common_libs_path = None env = os.environ.copy() if self._enable_common_pack_libs and pack_common_libs_path: env['PYTHONPATH'] = pack_common_libs_path + ':' + sandbox_python_path else: env['PYTHONPATH'] = sandbox_python_path # Include full api URL and API token specific to that sensor ttl = cfg.CONF.auth.service_token_ttl metadata = { 'service': 'sensors_container', 'sensor_path': sensor['file_path'], 'sensor_class': sensor['class_name'] } temporary_token = create_token(username='******', ttl=ttl, metadata=metadata, service=True) env[API_URL_ENV_VARIABLE_NAME] = get_full_public_api_url() env[AUTH_TOKEN_ENV_VARIABLE_NAME] = temporary_token.token # TODO 1: Purge temporary token when service stops or sensor process dies # TODO 2: Store metadata (wrapper process id) with the token and delete # tokens for old, dead processes on startup cmd = ' '.join(args) LOG.debug('Running sensor subprocess (cmd="%s")', cmd) # TODO: Intercept stdout and stderr for aggregated logging purposes try: process = subprocess.Popen(args=args, stdin=None, stdout=None, stderr=None, shell=False, env=env, preexec_fn=on_parent_exit('SIGTERM')) except Exception as e: cmd = ' '.join(args) message = ('Failed to spawn process for sensor %s ("%s"): %s' % (sensor_id, cmd, str(e))) raise Exception(message) self._processes[sensor_id] = process self._sensors[sensor_id] = sensor self._sensor_start_times[sensor_id] = int(time.time()) self._dispatch_trigger_for_sensor_spawn(sensor=sensor, process=process, cmd=cmd) return process
def run(self, action_parameters): LOG.debug('Running pythonrunner.') LOG.debug('Getting pack name.') pack = self.get_pack_ref() LOG.debug('Getting user.') user = self.get_user() LOG.debug('Serializing parameters.') serialized_parameters = json.dumps( action_parameters) if action_parameters else '' LOG.debug('Getting virtualenv_path.') virtualenv_path = get_sandbox_virtualenv_path(pack=pack) LOG.debug('Getting python path.') if self._sandbox: python_path = get_sandbox_python_binary_path(pack=pack) else: python_path = sys.executable LOG.debug('Checking virtualenv path.') if virtualenv_path and not os.path.isdir(virtualenv_path): format_values = {'pack': pack, 'virtualenv_path': virtualenv_path} msg = PACK_VIRTUALENV_DOESNT_EXIST % format_values LOG.error('virtualenv_path set but not a directory: %s', msg) raise Exception(msg) LOG.debug('Checking entry_point.') if not self.entry_point: LOG.error('Action "%s" is missing entry_point attribute' % (self.action.name)) raise Exception('Action "%s" is missing entry_point attribute' % (self.action.name)) # Note: We pass config as command line args so the actual wrapper process is standalone # and doesn't need access to db LOG.debug('Setting args.') args = [ python_path, '-u', # unbuffered mode so streaming mode works as expected WRAPPER_SCRIPT_PATH, '--pack=%s' % (pack), '--file-path=%s' % (self.entry_point), '--parameters=%s' % (serialized_parameters), '--user=%s' % (user), '--parent-args=%s' % (json.dumps(sys.argv[1:])), ] if self._config: args.append('--config=%s' % (json.dumps(self._config))) if self._log_level != 'debug': # We only pass --log-level parameter if non default log level value is specified args.append('--log-level=%s' % (self._log_level)) # We need to ensure all the st2 dependencies are also available to the # subprocess LOG.debug('Setting env.') env = os.environ.copy() env['PATH'] = get_sandbox_path(virtualenv_path=virtualenv_path) sandbox_python_path = get_sandbox_python_path( inherit_from_parent=True, inherit_parent_virtualenv=True) if self._enable_common_pack_libs: try: pack_common_libs_path = get_pack_common_libs_path_for_pack_ref( pack_ref=pack) except Exception: # There is no MongoDB connection available in Lambda and pack common lib # functionality is not also mandatory for Lambda so we simply ignore those errors. # Note: We should eventually refactor this code to make runner standalone and not # depend on a db connection (as it was in the past) - this param should be passed # to the runner by the action runner container pack_common_libs_path = None else: pack_common_libs_path = None if self._enable_common_pack_libs and pack_common_libs_path: env['PYTHONPATH'] = pack_common_libs_path + ':' + sandbox_python_path else: env['PYTHONPATH'] = sandbox_python_path # Include user provided environment variables (if any) user_env_vars = self._get_env_vars() env.update(user_env_vars) # Include common st2 environment variables st2_env_vars = self._get_common_action_env_variables() env.update(st2_env_vars) datastore_env_vars = self._get_datastore_access_env_vars() env.update(datastore_env_vars) stdout = StringIO() stderr = StringIO() store_execution_stdout_line = functools.partial( store_execution_output_data, output_type='stdout') store_execution_stderr_line = functools.partial( store_execution_output_data, output_type='stderr') read_and_store_stdout = make_read_and_store_stream_func( execution_db=self.execution, action_db=self.action, store_data_func=store_execution_stdout_line) read_and_store_stderr = make_read_and_store_stream_func( execution_db=self.execution, action_db=self.action, store_data_func=store_execution_stderr_line) command_string = list2cmdline(args) LOG.debug('Running command: PATH=%s PYTHONPATH=%s %s' % (env['PATH'], env['PYTHONPATH'], command_string)) exit_code, stdout, stderr, timed_out = run_command( cmd=args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, env=env, timeout=self._timeout, read_stdout_func=read_and_store_stdout, read_stderr_func=read_and_store_stderr, read_stdout_buffer=stdout, read_stderr_buffer=stderr) LOG.debug('Returning values: %s, %s, %s, %s' % (exit_code, stdout, stderr, timed_out)) LOG.debug('Returning.') return self._get_output_values(exit_code, stdout, stderr, timed_out)
def _spawn_sensor_process(self, sensor): """ Spawn a new process for the provided sensor. New process uses isolated Python binary from a virtual environment belonging to the sensor pack. """ sensor_id = self._get_sensor_id(sensor=sensor) pack_ref = sensor['pack'] virtualenv_path = get_sandbox_virtualenv_path(pack=pack_ref) python_path = get_sandbox_python_binary_path(pack=pack_ref) if virtualenv_path and not os.path.isdir(virtualenv_path): format_values = {'pack': sensor['pack'], 'virtualenv_path': virtualenv_path} msg = PACK_VIRTUALENV_DOESNT_EXIST % format_values raise Exception(msg) # NOTE: Running sensors using Python 3 virtual environments is not supported uses_python3, _ = is_pack_virtualenv_using_python3(pack=sensor['pack']) if uses_python3 and not six.PY3: format_values = {'pack': sensor['pack'], 'virtualenv_path': virtualenv_path} msg = PACK_VIRTUALENV_USES_PYTHON3 % format_values raise Exception(msg) trigger_type_refs = sensor['trigger_types'] or [] trigger_type_refs = ','.join(trigger_type_refs) parent_args = json.dumps(sys.argv[1:]) args = [ python_path, WRAPPER_SCRIPT_PATH, '--pack=%s' % (sensor['pack']), '--file-path=%s' % (sensor['file_path']), '--class-name=%s' % (sensor['class_name']), '--trigger-type-refs=%s' % (trigger_type_refs), '--parent-args=%s' % (parent_args) ] if sensor['poll_interval']: args.append('--poll-interval=%s' % (sensor['poll_interval'])) sandbox_python_path = get_sandbox_python_path(inherit_from_parent=True, inherit_parent_virtualenv=True) if self._enable_common_pack_libs: pack_common_libs_path = get_pack_common_libs_path_for_pack_ref(pack_ref=pack_ref) else: pack_common_libs_path = None env = os.environ.copy() if self._enable_common_pack_libs and pack_common_libs_path: env['PYTHONPATH'] = pack_common_libs_path + ':' + sandbox_python_path else: env['PYTHONPATH'] = sandbox_python_path # Include full api URL and API token specific to that sensor ttl = cfg.CONF.auth.service_token_ttl metadata = { 'service': 'sensors_container', 'sensor_path': sensor['file_path'], 'sensor_class': sensor['class_name'] } temporary_token = create_token(username='******', ttl=ttl, metadata=metadata, service=True) env[API_URL_ENV_VARIABLE_NAME] = get_full_public_api_url() env[AUTH_TOKEN_ENV_VARIABLE_NAME] = temporary_token.token # TODO 1: Purge temporary token when service stops or sensor process dies # TODO 2: Store metadata (wrapper process id) with the token and delete # tokens for old, dead processes on startup cmd = ' '.join(args) LOG.debug('Running sensor subprocess (cmd="%s")', cmd) # TODO: Intercept stdout and stderr for aggregated logging purposes try: process = subprocess.Popen(args=args, stdin=None, stdout=None, stderr=None, shell=False, env=env, preexec_fn=on_parent_exit('SIGTERM')) except Exception as e: cmd = ' '.join(args) message = ('Failed to spawn process for sensor %s ("%s"): %s' % (sensor_id, cmd, six.text_type(e))) raise Exception(message) self._processes[sensor_id] = process self._sensors[sensor_id] = sensor self._sensor_start_times[sensor_id] = int(time.time()) self._dispatch_trigger_for_sensor_spawn(sensor=sensor, process=process, cmd=cmd) return process
def _spawn_sensor_process(self, sensor): """ Spawn a new process for the provided sensor. New process uses isolated Python binary from a virtual environment belonging to the sensor pack. """ sensor_id = self._get_sensor_id(sensor=sensor) pack_ref = sensor["pack"] virtualenv_path = get_sandbox_virtualenv_path(pack=pack_ref) python_path = get_sandbox_python_binary_path(pack=pack_ref) if virtualenv_path and not os.path.isdir(virtualenv_path): format_values = { "pack": sensor["pack"], "virtualenv_path": virtualenv_path } msg = PACK_VIRTUALENV_DOESNT_EXIST % format_values raise Exception(msg) args = self._get_args_for_wrapper_script(python_binary=python_path, sensor=sensor) if self._enable_common_pack_libs: pack_common_libs_path = get_pack_common_libs_path_for_pack_ref( pack_ref=pack_ref) else: pack_common_libs_path = None env = os.environ.copy() sandbox_python_path = get_sandbox_python_path( inherit_from_parent=True, inherit_parent_virtualenv=True) if self._enable_common_pack_libs and pack_common_libs_path: env["PYTHONPATH"] = pack_common_libs_path + ":" + sandbox_python_path else: env["PYTHONPATH"] = sandbox_python_path if self._create_token: # Include full api URL and API token specific to that sensor LOG.debug("Creating temporary auth token for sensor %s" % (sensor["class_name"])) ttl = cfg.CONF.auth.service_token_ttl metadata = { "service": "sensors_container", "sensor_path": sensor["file_path"], "sensor_class": sensor["class_name"], } temporary_token = create_token(username="******", ttl=ttl, metadata=metadata, service=True) env[API_URL_ENV_VARIABLE_NAME] = get_full_public_api_url() env[AUTH_TOKEN_ENV_VARIABLE_NAME] = temporary_token.token # TODO 1: Purge temporary token when service stops or sensor process dies # TODO 2: Store metadata (wrapper process id) with the token and delete # tokens for old, dead processes on startup cmd = " ".join(args) LOG.debug('Running sensor subprocess (cmd="%s")', cmd) # TODO: Intercept stdout and stderr for aggregated logging purposes try: process = subprocess.Popen( args=args, stdin=None, stdout=None, stderr=None, shell=False, env=env, preexec_fn=on_parent_exit("SIGTERM"), ) except Exception as e: cmd = " ".join(args) message = 'Failed to spawn process for sensor %s ("%s"): %s' % ( sensor_id, cmd, six.text_type(e), ) raise Exception(message) self._processes[sensor_id] = process self._sensors[sensor_id] = sensor self._sensor_start_times[sensor_id] = int(time.time()) self._dispatch_trigger_for_sensor_spawn(sensor=sensor, process=process, cmd=cmd) return process