INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Render left blocks
def __render_left_panel(self): ''' Render left blocks ''' self.log.debug("Rendering left blocks") left_block = self.left_panel left_block.render() blank_space = self.left_panel_width - left_block.width lines = [] pre_space = ' ' * int(blank_space / 2) if ...
Main method to render screen view
def render_screen(self): ''' Main method to render screen view ''' self.term_width, self.term_height = get_terminal_size() self.log.debug( "Terminal size: %sx%s", self.term_width, self.term_height) self.right_panel_width = int( (self.term_width - len...
Add widget string to right panel of the screen
def add_info_widget(self, widget): ''' Add widget string to right panel of the screen ''' index = widget.get_index() while index in self.info_widgets.keys(): index += 1 self.info_widgets[widget.get_index()] = widget
Right - pad lines of block to equal width
def fill_rectangle(self, prepared): ''' Right-pad lines of block to equal width ''' result = [] width = max([self.clean_len(line) for line in prepared]) for line in prepared: spacer = ' ' * (width - self.clean_len(line)) result.append(line + (self.screen.markup....
Calculate wisible length of string
def clean_len(self, line): ''' Calculate wisible length of string ''' if isinstance(line, basestring): return len(self.screen.markup.clean_markup(line)) elif isinstance(line, tuple) or isinstance(line, list): markups = self.screen.markup.get_markup_vars() le...
Creates load plan timestamps generator
def create(instances_schedule): ''' Creates load plan timestamps generator >>> from util import take >>> take(7, LoadPlanBuilder().ramp(5, 4000).create()) [0, 1000, 2000, 3000, 4000, 0, 0] >>> take(7, create(['ramp(5, 4s)'])) [0, 1000, 2000, 3000, 4000, 0, 0] >>> take(12, create(['ra...
format level str
def get_level_str(self): ''' format level str ''' if self.is_relative: level_str = str(self.level) + "%" else: level_str = self.level return level_str
formula for measurement error sqrt ( ( sum ( 1 n ( k_i - <k > ) ** 2 )/ ( n * ( n - 1 )))
def calc_measurement_error(self, tangents): ''' formula for measurement error sqrt ( (sum(1, n, (k_i - <k>)**2) / (n*(n-1))) ''' if len(tangents) < 2: return 0.0 avg_tan = float(sum(tangents) / len(tangents)) numerator = float() for i in tang...
add right panel widget
def add_info_widget(self, widget): ''' add right panel widget ''' if not self.screen: self.log.debug("No screen instance to add widget") else: self.screen.add_info_widget(widget)
clean markup from string
def clean_markup(self, orig_str): ''' clean markup from string ''' for val in self.get_markup_vars(): orig_str = orig_str.replace(val, '') return orig_str
Send request to writer service.
def __make_writer_request( self, params=None, json=None, http_method="POST", trace=False): ''' Send request to writer service. ''' request = requests.Request( http_method, self.writer_url, par...
: return: job_nr upload_token: rtype: tuple
def new_job( self, task, person, tank, target_host, target_port, loadscheme=None, detailed_time=None, notify_list=None, trace=False): """ :return: job_nr, upload_token :rtype: ...
: returns: { plugin_name: plugin_class... }: rtype: dict
def plugins(self): """ :returns: {plugin_name: plugin_class, ...} :rtype: dict """ if self._plugins is None: self.load_plugins() if self._plugins is None: self._plugins = {} return self._plugins
Tells core to take plugin options and instantiate plugin classes
def load_plugins(self): """ Tells core to take plugin options and instantiate plugin classes """ logger.info("Loading plugins...") for (plugin_name, plugin_path, plugin_cfg) in self.config.plugins: logger.debug("Loading plugin %s from %s", plugin_name, plugin_path) ...
Call configure () on all plugins
def plugins_configure(self): """ Call configure() on all plugins """ self.publish("core", "stage", "configure") logger.info("Configuring plugins...") self.taskset_affinity = self.get_option(self.SECTION, 'affinity') if self.taskset_affinity: self.__setu...
Call is_test_finished () on all plugins till one of them initiates exit
def wait_for_finish(self): """ Call is_test_finished() on all plugins 'till one of them initiates exit """ if not self.interrupted.is_set(): logger.info("Waiting for test to finish...") logger.info('Artifacts dir: {dir}'.format(dir=self.artifacts_dir)) ...
Call post_process () on all plugins
def plugins_post_process(self, retcode): """ Call post_process() on all plugins """ logger.info("Post-processing test...") self.publish("core", "stage", "post_process") for plugin in self.plugins.values(): logger.debug("Post-process %s", plugin) tr...
if pid specified: set process w/ pid pid CPU affinity to specified affinity core ( s ) if args specified: modify list of args for Popen to start w/ taskset w/ affinity affinity
def __setup_taskset(self, affinity, pid=None, args=None): """ if pid specified: set process w/ pid `pid` CPU affinity to specified `affinity` core(s) if args specified: modify list of args for Popen to start w/ taskset w/ affinity `affinity` """ self.taskset_path = self.get_option(se...
Retrieve a plugin of desired class KeyError raised otherwise
def get_plugin_of_type(self, plugin_class): """ Retrieve a plugin of desired class, KeyError raised otherwise """ logger.debug("Searching for plugin: %s", plugin_class) matches = [plugin for plugin in self.plugins.values() if isinstance(plugin, plugin_class)] if matches: ...
Retrieve a list of plugins of desired class KeyError raised otherwise
def get_plugins_of_type(self, plugin_class): """ Retrieve a list of plugins of desired class, KeyError raised otherwise """ logger.debug("Searching for plugins: %s", plugin_class) matches = [plugin for plugin in self.plugins.values() if isinstance(plugin, plugin_class)] i...
Move or copy single file to artifacts dir
def __collect_file(self, filename, keep_original=False): """ Move or copy single file to artifacts dir """ dest = self.artifacts_dir + '/' + os.path.basename(filename) logger.debug("Collecting file: %s to %s", filename, dest) if not filename or not os.path.exists(filename...
Add file to be stored as result artifact on post - process phase
def add_artifact_file(self, filename, keep_original=False): """ Add file to be stored as result artifact on post-process phase """ if filename: logger.debug( "Adding artifact file to collect (keep=%s): %s", keep_original, filename) ...
Generate temp file name in artifacts base dir and close temp file handle
def mkstemp(self, suffix, prefix, directory=None): """ Generate temp file name in artifacts base dir and close temp file handle """ if not directory: directory = self.artifacts_dir fd, fname = tempfile.mkstemp(suffix, prefix, directory) os.close(fd) ...
Call close () for all plugins
def close(self): """ Call close() for all plugins """ logger.info("Close allocated resources...") for plugin in self.plugins.values(): logger.debug("Close %s", plugin) try: plugin.close() except Exception as ex: ...
Read configs set into storage
def load_files(self, configs): """ Read configs set into storage """ logger.debug("Reading configs: %s", configs) config_filenames = [resource.resource_filename(config) for config in configs] try: self.config.read(config_filenames) except Exception as e...
Flush current stat to file
def flush(self, filename=None): """ Flush current stat to file """ if not filename: filename = self.file if filename: with open(filename, 'w') as handle: self.config.write(handle)
Get options list with requested prefix
def get_options(self, section, prefix=''): """ Get options list with requested prefix """ res = [] try: for option in self.config.options(section): if not prefix or option.find(prefix) == 0: res += [( option[len(prefix):], s...
return sections with specified prefix
def find_sections(self, prefix): """ return sections with specified prefix """ res = [] for section in self.config.sections(): if section.startswith(prefix): res.append(section) return res
Return all items found in this chunk
def _decode_stat_data(self, chunk): """ Return all items found in this chunk """ for date_str, statistics in chunk.iteritems(): date_obj = datetime.datetime.strptime( date_str.split(".")[0], '%Y-%m-%d %H:%M:%S') chunk_date = int(time.mktime(date_ob...
: rtype: PhantomConfig
def phantom(self): """ :rtype: PhantomConfig """ if not self._phantom: self._phantom = PhantomConfig(self.core, self.cfg, self.stat_log) self._phantom.read_config() return self._phantom
returns info object
def get_info(self): """ returns info object """ if not self.cached_info: if not self.phantom: return None self.cached_info = self.phantom.get_info() return self.cached_info
Prepare for monitoring - install agents etc
def prepare(self): """Prepare for monitoring - install agents etc""" # Parse config agent_configs = [] if self.config: agent_configs = self.config_manager.getconfig( self.config, self.default_target) # Creating agent for hosts for config in a...
Start agents
def start(self): """ Start agents execute popen of agent.py on target and start output reader thread. """ [agent.start() for agent in self.agents] [agent.reader_thread.start() for agent in self.agents]
Poll agents for data
def poll(self): """ Poll agents for data """ start_time = time.time() for agent in self.agents: for collect in agent.reader: # don't crush if trash or traceback came from agent to stdout if not collect: return 0 ...
Shutdown agents
def stop(self): """Shutdown agents""" logger.debug("Uninstalling monitoring agents") for agent in self.agents: log_filename, data_filename = agent.uninstall() self.artifact_files.append(log_filename) self.artifact_files.append(data_filename) for agent ...
sends pending data set to listeners
def send_collected_data(self): """sends pending data set to listeners""" data = self.__collected_data self.__collected_data = [] for listener in self.listeners: # deep copy to ensure each listener gets it's own copy listener.monitoring_data(copy.deepcopy(data))
we need to be flexible in order to determine which plugin s configuration specified and make appropriate configs to metrics collector
def __detect_configuration(self): """ we need to be flexible in order to determine which plugin's configuration specified and make appropriate configs to metrics collector :return: SECTION name or None for defaults """ try: is_telegraf = self.core.get_option(...
store metric in data tree and calc offset signs
def __handle_data_items(self, host, data): """ store metric in data tree and calc offset signs sign < 0 is CYAN, means metric value is lower then previous, sign > 1 is YELLOW, means metric value is higher then prevoius, sign == 0 is WHITE, means initial or equal metric value """...
decode agents jsons count diffs
def _decode_agents_data(self, block): """ decode agents jsons, count diffs """ collect = [] if block: for chunk in block.split('\n'): try: if chunk: prepared_results = {} jsn = json.lo...
Start subscribing channels. If the necessary connection isn t open yet it opens now.
async def subscribe(self, channels): '''Start subscribing channels. If the necessary connection isn't open yet, it opens now. ''' ws_channels = [] nats_channels = [] for c in channels: if c.startswith(('Q.', 'T.', 'A.', 'AM.',)): nats_channels....
Run forever and block until exception is rasised. initial_channels is the channels to start with.
def run(self, initial_channels=[]): '''Run forever and block until exception is rasised. initial_channels is the channels to start with. ''' loop = asyncio.get_event_loop() try: loop.run_until_complete(self.subscribe(initial_channels)) loop.run_forever() ...
Close any of open connections
async def close(self): '''Close any of open connections''' if self._ws is not None: await self._ws.close() if self.polygon is not None: await self.polygon.close()
## Experimental
def df(self): '''## Experimental ''' if not hasattr(self, '_df'): dfs = [] for symbol, bars in self.items(): df = bars.df.copy() df.columns = pd.MultiIndex.from_product( [[symbol, ], df.columns]) dfs.append(df) ...
Perform one request possibly raising RetryException in the case the response is 429. Otherwise if error text contain code string then it decodes to json object and returns APIError. Returns the body json in the 200 status.
def _one_request(self, method, url, opts, retry): ''' Perform one request, possibly raising RetryException in the case the response is 429. Otherwise, if error text contain "code" string, then it decodes to json object and returns APIError. Returns the body json in the 200 status...
Get a list of orders https:// docs. alpaca. markets/ web - api/ orders/ #get - a - list - of - orders
def list_orders(self, status=None, limit=None, after=None, until=None, direction=None, params=None): ''' Get a list of orders https://docs.alpaca.markets/web-api/orders/#get-a-list-of-orders ''' if params is None: params = dict() if limit i...
Request a new order
def submit_order(self, symbol, qty, side, type, time_in_force, limit_price=None, stop_price=None, client_order_id=None): '''Request a new order''' params = { 'symbol': symbol, 'qty': qty, 'side': side, 'type': type, 'time_i...
Get an order
def get_order(self, order_id): '''Get an order''' resp = self.get('/orders/{}'.format(order_id)) return Order(resp)
Get an open position
def get_position(self, symbol): '''Get an open position''' resp = self.get('/positions/{}'.format(symbol)) return Position(resp)
Get a list of assets
def list_assets(self, status=None, asset_class=None): '''Get a list of assets''' params = { 'status': status, 'assert_class': asset_class, } resp = self.get('/assets', params) return [Asset(o) for o in resp]
Get an asset
def get_asset(self, symbol): '''Get an asset''' resp = self.get('/assets/{}'.format(symbol)) return Asset(resp)
Get BarSet ( dict [ str ] - > list [ Bar ] ) The parameter symbols can be either a comma - split string or a list of string. Each symbol becomes the key of the returned value.
def get_barset(self, symbols, timeframe, limit=None, start=None, end=None, after=None, until=None): '''Get BarSet(dict[str]->list[Bar]) The parameter symbols can be either...
( decorator ) Create a simple solid.
def lambda_solid(name=None, inputs=None, output=None, description=None): '''(decorator) Create a simple solid. This shortcut allows the creation of simple solids that do not require configuration and whose implementations do not require a context. Lambda solids take inputs and produce a single output....
( decorator ) Create a solid with specified parameters.
def solid(name=None, inputs=None, outputs=None, config_field=None, description=None): '''(decorator) Create a solid with specified parameters. This shortcut simplifies the core solid API by exploding arguments into kwargs of the transform function and omitting additional parameters when they are not needed...
Create a new MultipleResults object from a dictionary. Keys of the dictionary are unpacked into result names. Args: result_dict ( dict ) - The dictionary to unpack. Returns: (: py: class: MultipleResults <dagster. MultipleResults > ) A new MultipleResults object
def from_dict(result_dict): '''Create a new ``MultipleResults`` object from a dictionary. Keys of the dictionary are unpacked into result names. Args: result_dict (dict) - The dictionary to unpack. Returns: (:py:class:`MultipleResults <d...
This captures a common pattern of fanning out a single value to N steps where each step has similar structure. The strict requirement here is that each step must provide an output named the parameters parallel_step_output.
def create_joining_subplan( pipeline_def, solid, join_step_key, parallel_steps, parallel_step_output ): ''' This captures a common pattern of fanning out a single value to N steps, where each step has similar structure. The strict requirement here is that each step must provide an output named the p...
gunzips/ path/ to/ foo. gz to/ path/ to/ raw/ 2019/ 01/ 01/ data. json
def gunzipper(gzip_file): '''gunzips /path/to/foo.gz to /path/to/raw/2019/01/01/data.json ''' # TODO: take date as an input path_prefix = os.path.dirname(gzip_file) output_folder = os.path.join(path_prefix, 'raw/2019/01/01') outfile = os.path.join(output_folder, 'data.json') if not safe_is...
Ensures argument obj is a dictionary and enforces that the keys/ values conform to the types specified by key_type value_type.
def _check_key_value_types(obj, key_type, value_type, key_check=isinstance, value_check=isinstance): '''Ensures argument obj is a dictionary, and enforces that the keys/values conform to the types specified by key_type, value_type. ''' if not isinstance(obj, dict): raise_with_traceback(_type_mis...
Ensures argument obj is a native Python dictionary raises an exception if not and otherwise returns obj.
def dict_param(obj, param_name, key_type=None, value_type=None): '''Ensures argument obj is a native Python dictionary, raises an exception if not, and otherwise returns obj. ''' if not isinstance(obj, dict): raise_with_traceback(_param_type_mismatch_exception(obj, dict, param_name)) if not...
Ensures argument obj is either a dictionary or None ; if the latter instantiates an empty dictionary.
def opt_dict_param(obj, param_name, key_type=None, value_type=None, value_class=None): '''Ensures argument obj is either a dictionary or None; if the latter, instantiates an empty dictionary. ''' if obj is not None and not isinstance(obj, dict): raise_with_traceback(_param_type_mismatch_exceptio...
Callback receives a stream of event_records
def construct_event_logger(event_record_callback): ''' Callback receives a stream of event_records ''' check.callable_param(event_record_callback, 'event_record_callback') return construct_single_handler_logger( 'event-logger', DEBUG, StructuredLoggerHandler( lam...
Record a stream of event records to json
def construct_json_event_logger(json_path): '''Record a stream of event records to json''' check.str_param(json_path, 'json_path') return construct_single_handler_logger( "json-event-record-logger", DEBUG, JsonEventLoggerHandler( json_path, lambda record: cons...
Read a config file and instantiate the RCParser.
def from_file(cls, path=None): """Read a config file and instantiate the RCParser. Create new :class:`configparser.ConfigParser` for the given **path** and instantiate the :class:`RCParser` with the ConfigParser as :attr:`config` attribute. If the **path** doesn't exist, raise ...
Get config dictionary for the given repository.
def get_repository_config(self, repository): """Get config dictionary for the given repository. If the repository section is not found in the config file, return ``None``. If the file is invalid, raise :exc:`configparser.Error`. Otherwise return a dictionary with: * `...
Assigned parameters into the appropiate place in the input notebook Args: nb ( NotebookNode ): Executable notebook object parameters ( dict ): Arbitrary keyword arguments to pass to the notebook parameters.
def replace_parameters(context, nb, parameters): # Uma: This is a copy-paste from papermill papermill/execute.py:104 (execute_parameters). # Typically, papermill injects the injected-parameters cell *below* the parameters cell # but we want to *replace* the parameters cell, which is what this function does....
Creates a solid with the given number of ( meaningless ) inputs and outputs.
def nonce_solid(name, n_inputs, n_outputs): """Creates a solid with the given number of (meaningless) inputs and outputs. Config controls the behavior of the nonce solid.""" @solid( name=name, inputs=[ InputDefinition(name='input_{}'.format(i)) for i in range(n_inputs) ...
This recursive descent thing formats a config dict for GraphQL.
def format_config_for_graphql(config): '''This recursive descent thing formats a config dict for GraphQL.''' def _format_config_subdict(config, current_indent=0): check.dict_param(config, 'config', key_type=str) printer = IndentingStringIoPrinter(indent_level=2, current_indent=current_indent) ...
Get a pipeline by name. Only constructs that pipeline and caches it.
def get_pipeline(self, name): '''Get a pipeline by name. Only constructs that pipeline and caches it. Args: name (str): Name of the pipeline to retriever Returns: PipelineDefinition: Instance of PipelineDefinition with that name. ''' check.str_param(name...
Return all pipelines as a list
def get_all_pipelines(self): '''Return all pipelines as a list Returns: List[PipelineDefinition]: ''' pipelines = list(map(self.get_pipeline, self.pipeline_dict.keys())) # This does uniqueness check self._construct_solid_defs(pipelines) return pipeli...
Spark configuration.
def define_spark_config(): '''Spark configuration. See the Spark documentation for reference: https://spark.apache.org/docs/latest/submitting-applications.html ''' master_url = Field( String, description='The master URL for the cluster (e.g. spark://23.195.26.187:7077)', ...
This function polls the process until it returns a valid item or returns PROCESS_DEAD_AND_QUEUE_EMPTY if it is in a state where the process has terminated and the queue is empty
def get_next_event(process, queue): ''' This function polls the process until it returns a valid item or returns PROCESS_DEAD_AND_QUEUE_EMPTY if it is in a state where the process has terminated and the queue is empty Warning: if the child process is in an infinite loop. This will also infinite...
Execute pipeline using message queue as a transport
def execute_pipeline_through_queue( repository_info, pipeline_name, solid_subset, environment_dict, run_id, message_queue, reexecution_config, step_keys_to_execute, ): """ Execute pipeline using message queue as a transport """ message_queue.put(ProcessStartedSentinel(os...
Waits until all there are no processes enqueued.
def join(self): '''Waits until all there are no processes enqueued.''' while True: with self._processes_lock: if not self._processes and self._processing_semaphore.locked(): return True gevent.sleep(0.1)
The schema for configuration data that describes the type optionality defaults and description.
def Field( dagster_type, default_value=FIELD_NO_DEFAULT_PROVIDED, is_optional=INFER_OPTIONAL_COMPOSITE_FIELD, is_secret=False, description=None, ): ''' The schema for configuration data that describes the type, optionality, defaults, and description. Args: dagster_type (DagsterT...
Snowflake configuration.
def define_snowflake_config(): '''Snowflake configuration. See the Snowflake documentation for reference: https://docs.snowflake.net/manuals/user-guide/python-connector-api.html ''' account = Field( String, description='Your Snowflake account name. For more details, see https:...
Builds the execution plan.
def build(self, pipeline_def, artifacts_persisted): '''Builds the execution plan. ''' # Construct dependency dictionary deps = {step.key: set() for step in self.steps} for step in self.steps: for step_input in step.step_inputs: deps[step.key].add(ste...
Here we build a new ExecutionPlan from a pipeline definition and the environment config.
def build(pipeline_def, environment_config): '''Here we build a new ExecutionPlan from a pipeline definition and the environment config. To do this, we iterate through the pipeline's solids in topological order, and hand off the execution steps for each solid to a companion _PlanBuilder object....
Build a pipeline which is a subset of another pipeline. Only includes the solids which are in solid_names.
def _build_sub_pipeline(pipeline_def, solid_names): ''' Build a pipeline which is a subset of another pipeline. Only includes the solids which are in solid_names. ''' check.inst_param(pipeline_def, 'pipeline_def', PipelineDefinition) check.list_param(solid_names, 'solid_names', of_type=str) ...
Return the solid named name. Throws if it does not exist.
def solid_named(self, name): '''Return the solid named "name". Throws if it does not exist. Args: name (str): Name of solid Returns: SolidDefinition: SolidDefinition with correct name. ''' check.str_param(name, 'name') if name not in self._solid_...
Get the shell commands we ll use to actually build and publish a package to PyPI.
def construct_publish_comands(additional_steps=None, nightly=False): '''Get the shell commands we'll use to actually build and publish a package to PyPI.''' publish_commands = ( ['rm -rf dist'] + (additional_steps if additional_steps else []) + [ 'python setup.py sdist bdist_...
Publishes ( uploads ) all submodules to PyPI.
def publish(nightly): """Publishes (uploads) all submodules to PyPI. Appropriate credentials must be available to twine, e.g. in a ~/.pypirc file, and users must be permissioned as maintainers on the PyPI projects. Publishing will fail if versions (git tags and Python versions) are not in lockstep, if ...
Tags all submodules for a new release.
def release(version): """Tags all submodules for a new release. Ensures that git tags, as well as the version.py files in each submodule, agree and that the new version is strictly greater than the current version. Will fail if the new version is not an increment (following PEP 440). Creates a new git ...
Create a context definition from a pre - existing context. This can be useful in testing contexts where you may want to create a context manually and then pass it into a one - off PipelineDefinition
def passthrough_context_definition(context_params): '''Create a context definition from a pre-existing context. This can be useful in testing contexts where you may want to create a context manually and then pass it into a one-off PipelineDefinition Args: context (ExecutionC...
A decorator for annotating a function that can take the selected properties from a config_value in to an instance of a custom type.
def input_selector_schema(config_cls): ''' A decorator for annotating a function that can take the selected properties from a ``config_value`` in to an instance of a custom type. Args: config_cls (Selector) ''' config_type = resolve_config_cls_arg(config_cls) check.param_invariant(c...
A decorator for a annotating a function that can take the selected properties of a config_value and an instance of a custom type and materialize it.
def output_selector_schema(config_cls): ''' A decorator for a annotating a function that can take the selected properties of a ``config_value`` and an instance of a custom type and materialize it. Args: config_cls (Selector): ''' config_type = resolve_config_cls_arg(config_cls) chec...
Automagically wrap a block of text.
def block(self, text, prefix=''): '''Automagically wrap a block of text.''' wrapper = TextWrapper( width=self.line_length - len(self.current_indent_str), initial_indent=prefix, subsequent_indent=prefix, break_long_words=False, break_on_hyphens=...
The following fields are shared between both QueryJobConfig and LoadJobConfig.
def _define_shared_fields(): '''The following fields are shared between both QueryJobConfig and LoadJobConfig. ''' clustering_fields = Field( List(String), description='''Fields defining clustering for the table (Defaults to None). Clustering fields are immutable after tab...
See: https:// googleapis. github. io/ google - cloud - python/ latest/ bigquery/ generated/ google. cloud. bigquery. job. QueryJobConfig. html
def define_bigquery_query_config(): '''See: https://googleapis.github.io/google-cloud-python/latest/bigquery/generated/google.cloud.bigquery.job.QueryJobConfig.html ''' sf = _define_shared_fields() allow_large_results = Field( Bool, description='''Allow large query results tables (l...
Return a new solid that executes and materializes a SQL select statement.
def sql_solid(name, select_statement, materialization_strategy, table_name=None, inputs=None): '''Return a new solid that executes and materializes a SQL select statement. Args: name (str): The name of the new solid. select_statement (str): The select statement to execute. materializati...
Download an object from s3.
def download_from_s3(context): '''Download an object from s3. Args: info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource. Returns: str: The path to the downloaded object. ''' target_file = context.solid_config['target_file'] return con...
Upload a file to s3.
def upload_to_s3(context, file_obj): '''Upload a file to s3. Args: info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource. Returns: (str, str): The bucket and key to which the file was uploaded. ''' bucket = context.solid_config['bucket'] ...
Wraps the execution of user - space code in an error boundary. This places a uniform policy around an user code invoked by the framework. This ensures that all user errors are wrapped in the DagsterUserCodeExecutionError and that the original stack trace of the user error is preserved so that it can be reported without...
def user_code_error_boundary(error_cls, msg, **kwargs): ''' Wraps the execution of user-space code in an error boundary. This places a uniform policy around an user code invoked by the framework. This ensures that all user errors are wrapped in the DagsterUserCodeExecutionError, and that the original st...
The missing mkdir - p functionality in os.
def mkdir_p(newdir, mode=0o777): """The missing mkdir -p functionality in os.""" try: os.makedirs(newdir, mode) except OSError as err: # Reraise the error unless it's about an already existing directory if err.errno != errno.EEXIST or not os.path.isdir(newdir): raise
Wraps the output of a user provided function that may yield or return a value and returns a generator that asserts it only yields a single value.
def user_code_context_manager(user_fn, error_cls, msg): '''Wraps the output of a user provided function that may yield or return a value and returns a generator that asserts it only yields a single value. ''' check.callable_param(user_fn, 'user_fn') check.subclass_param(error_cls, 'error_cls', Dagst...
Construct the run storage for this pipeline. Our rules are the following:
def construct_run_storage(run_config, environment_config): ''' Construct the run storage for this pipeline. Our rules are the following: If the RunConfig has a storage_mode provided, we use that. Then we fallback to environment config. If there is no config, we default to in memory storage. This ...
In the event of pipeline initialization failure we want to be able to log the failure without a dependency on the ExecutionContext to initialize DagsterLog
def _create_context_free_log(run_config, pipeline_def): '''In the event of pipeline initialization failure, we want to be able to log the failure without a dependency on the ExecutionContext to initialize DagsterLog ''' check.inst_param(run_config, 'run_config', RunConfig) check.inst_param(pipeline_...
Returns iterator that yields: py: class: SolidExecutionResult for each solid executed in the pipeline.
def execute_pipeline_iterator(pipeline, environment_dict=None, run_config=None): '''Returns iterator that yields :py:class:`SolidExecutionResult` for each solid executed in the pipeline. This is intended to allow the caller to do things between each executed node. For the 'synchronous' API, see :py:fun...
Synchronous version of: py: func: execute_pipeline_iterator.
def execute_pipeline(pipeline, environment_dict=None, run_config=None): ''' "Synchronous" version of :py:func:`execute_pipeline_iterator`. Note: raise_on_error is very useful in testing contexts when not testing for error conditions Parameters: pipeline (PipelineDefinition): Pipeline to run ...
Get a: py: class: SolidExecutionResult for a given solid name.
def result_for_solid(self, name): '''Get a :py:class:`SolidExecutionResult` for a given solid name. ''' check.str_param(name, 'name') if not self.pipeline.has_solid(name): raise DagsterInvariantViolationError( 'Try to get result for solid {name} in {pipeline}...
Whether the solid execution was successful
def success(self): '''Whether the solid execution was successful''' any_success = False for step_event in itertools.chain( self.input_expectations, self.output_expectations, self.transforms ): if step_event.event_type == DagsterEventType.STEP_FAILURE: ...
Whether the solid execution was skipped
def skipped(self): '''Whether the solid execution was skipped''' return all( [ step_event.event_type == DagsterEventType.STEP_SKIPPED for step_event in itertools.chain( self.input_expectations, self.output_expectations, self.transforms ...