INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
If the target table doesn t exist self. create_table will be called to attempt to create the table.
def run(self): """ If the target table doesn't exist, self.create_table will be called to attempt to create the table. """ if not (self.table): raise Exception("table need to be specified") path = self.s3_load_path() output = self.output() con...
Defines copying from s3 into redshift.
def copy(self, cursor, f): """ Defines copying from s3 into redshift. If both key-based and role-based credentials are provided, role-based will be used. """ logger.info("Inserting file: %s", f) colnames = '' if self.columns and len(self.columns) > 0: ...
Determine whether the schema already exists.
def does_schema_exist(self, connection): """ Determine whether the schema already exists. """ if '.' in self.table: query = ("select 1 as schema_exists " "from pg_namespace " "where nspname = lower(%s) limit 1") else: ...
Determine whether the table already exists.
def does_table_exist(self, connection): """ Determine whether the table already exists. """ if '.' in self.table: query = ("select 1 as table_exists " "from information_schema.tables " "where table_schema = lower(%s) and table_name =...
Perform pre - copy sql - such as creating table truncating or removing data older than x.
def init_copy(self, connection): """ Perform pre-copy sql - such as creating table, truncating, or removing data older than x. """ if not self.does_schema_exist(connection): logger.info("Creating schema for %s", self.table) self.create_schema(connection) ...
Performs post - copy sql - such as cleansing data inserting into production table ( if copied to temp table ) etc.
def post_copy(self, cursor): """ Performs post-copy sql - such as cleansing data, inserting into production table (if copied to temp table), etc. """ logger.info('Executing post copy queries') for query in self.queries: cursor.execute(query)
Performs post - copy to fill metadata columns.
def post_copy_metacolums(self, cursor): """ Performs post-copy to fill metadata columns. """ logger.info('Executing post copy metadata queries') for query in self.metadata_queries: cursor.execute(query)
Defines copying JSON from s3 into redshift.
def copy(self, cursor, f): """ Defines copying JSON from s3 into redshift. """ logger.info("Inserting file: %s", f) cursor.execute(""" COPY %s from '%s' CREDENTIALS '%s' JSON AS '%s' %s %s ;""" % (self.table, f, self._credentials(), ...
Returns a RedshiftTarget representing the inserted dataset.
def output(self): """ Returns a RedshiftTarget representing the inserted dataset. Normally you don't override this. """ # uses class name as a meta-table return RedshiftTarget( host=self.host, database=self.database, user=self.user, ...
Kill any open Redshift sessions for the given database.
def run(self): """ Kill any open Redshift sessions for the given database. """ connection = self.output().connect() # kill any sessions other than ours and # internal Redshift sessions (rdsdb) query = ("select pg_terminate_backend(process) " "from...
Returns a list of dates in this date interval.
def dates(self): ''' Returns a list of dates in this date interval.''' dates = [] d = self.date_a while d < self.date_b: dates.append(d) d += datetime.timedelta(1) return dates
Same as dates () but returns 24 times more info: one for each hour.
def hours(self): ''' Same as dates() but returns 24 times more info: one for each hour.''' for date in self.dates(): for hour in xrange(24): yield datetime.datetime.combine(date, datetime.time(hour))
The execution of this task will write 4 lines of data on this task s target output.
def run(self): """ The execution of this task will write 4 lines of data on this task's target output. """ with self.output().open('w') as outfile: print("data 0 200 10 50 60", file=outfile) print("data 1 190 9 52 60", file=outfile) print("data 2 200 1...
Copies the contents of a single file path to dest
def copy(self, path, dest, raise_if_exists=False): """ Copies the contents of a single file path to dest """ if raise_if_exists and dest in self.get_all_data(): raise RuntimeError('Destination exists: %s' % path) contents = self.get_all_data()[path] self.get_a...
Removes the given mockfile. skip_trash doesn t have any meaning.
def remove(self, path, recursive=True, skip_trash=True): """ Removes the given mockfile. skip_trash doesn't have any meaning. """ if recursive: to_delete = [] for s in self.get_all_data().keys(): if s.startswith(path): to_delete...
Moves a single file from path to dest
def move(self, path, dest, raise_if_exists=False): """ Moves a single file from path to dest """ if raise_if_exists and dest in self.get_all_data(): raise RuntimeError('Destination exists: %s' % path) contents = self.get_all_data().pop(path) self.get_all_data(...
listdir does a prefix match of self. get_all_data () but doesn t yet support globs.
def listdir(self, path): """ listdir does a prefix match of self.get_all_data(), but doesn't yet support globs. """ return [s for s in self.get_all_data().keys() if s.startswith(path)]
Call MockFileSystem s move command
def move(self, path, raise_if_exists=False): """ Call MockFileSystem's move command """ self.fs.move(self.path, path, raise_if_exists)
Recursively walks Mapping s and list s and converts them to _FrozenOrderedDict and tuples respectively.
def _recursively_freeze(value): """ Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively. """ if isinstance(value, Mapping): return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items())) elif isinstance(val...
Loads the default from the config. Returns _no_value if it doesn t exist
def _get_value_from_config(self, section, name): """Loads the default from the config. Returns _no_value if it doesn't exist""" conf = configuration.get_config() try: value = conf.get(section, name) except (NoSectionError, NoOptionError, KeyError): return _no_va...
Yield the parameter values with optional deprecation warning as second tuple value.
def _value_iterator(self, task_name, param_name): """ Yield the parameter values, with optional deprecation warning as second tuple value. The parameter value will be whatever non-_no_value that is yielded first. """ cp_parser = CmdlineParser.get_instance() if cp_parser:...
Parse a list of values from the scheduler.
def _parse_list(self, xs): """ Parse a list of values from the scheduler. Only possible if this is_batchable() is True. This will combine the list into a single parameter value using batch method. This should never need to be overridden. :param xs: list of values to parse and c...
Parses a date string formatted like YYYY - MM - DD.
def parse(self, s): """ Parses a date string formatted like ``YYYY-MM-DD``. """ return datetime.datetime.strptime(s, self.date_format).date()
Converts the date to a string using the: py: attr: ~_DateParameterBase. date_format.
def serialize(self, dt): """ Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`. """ if dt is None: return str(dt) return dt.strftime(self.date_format)
Add months months to date.
def _add_months(self, date, months): """ Add ``months`` months to ``date``. Unfortunately we can't use timedeltas to add months because timedelta counts in days and there's no foolproof way to add N months in days without counting the number of days per month. """ ...
Clamp dt to every Nth: py: attr: ~_DatetimeParameterBase. interval starting at: py: attr: ~_DatetimeParameterBase. start.
def normalize(self, dt): """ Clamp dt to every Nth :py:attr:`~_DatetimeParameterBase.interval` starting at :py:attr:`~_DatetimeParameterBase.start`. """ if dt is None: return None dt = self._convert_to_dt(dt) dt = dt.replace(microsecond=0) # remove ...
Parses a bool from the string matching true or false ignoring case.
def parse(self, val): """ Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case. """ s = str(val).lower() if s == "true": return True elif s == "false": return False else: raise ValueError("cannot interpret...
Parses a: py: class: ~luigi. date_interval. DateInterval from the input.
def parse(self, s): """ Parses a :py:class:`~luigi.date_interval.DateInterval` from the input. see :py:mod:`luigi.date_interval` for details on the parsing of DateIntervals. """ # TODO: can we use xml.utils.iso8601 or something similar? from luigi import date_...
Parses a time delta from the input.
def parse(self, input): """ Parses a time delta from the input. See :py:class:`TimeDeltaParameter` for details on supported formats. """ result = self._parseIso8601(input) if not result: result = self._parseSimple(input) if result is not None: ...
Converts datetime. timedelta to a string
def serialize(self, x): """ Converts datetime.timedelta to a string :param x: the value to serialize. """ weeks = x.days // 7 days = x.days % 7 hours = x.seconds // 3600 minutes = (x.seconds % 3600) // 60 seconds = (x.seconds % 3600) % 60 ...
Parse an individual value from the input.
def parse(self, x): """ Parse an individual value from the input. :param str x: the value to parse. :return: the parsed value. """ # Since the result of json.dumps(tuple) differs from a tuple string, we must handle either case. # A tuple string may come from a co...
1. count the words for each of the: py: meth: ~. InputText. output targets created by: py: class: ~. InputText 2. write the count into the: py: meth: ~. WordCount. output target
def run(self): """ 1. count the words for each of the :py:meth:`~.InputText.output` targets created by :py:class:`~.InputText` 2. write the count into the :py:meth:`~.WordCount.output` target """ count = {} # NOTE: self.input() actually returns an element for the InputTe...
Create a tar archive which will contain the files for the packages listed in packages.
def create_packages_archive(packages, filename): """ Create a tar archive which will contain the files for the packages listed in packages. """ import tarfile tar = tarfile.open(filename, "w") def add(src, dst): logger.debug('adding to tar: %s -> %s', src, dst) tar.add(src, dst)...
A simple generator which flattens a sequence.
def flatten(sequence): """ A simple generator which flattens a sequence. Only one level is flattened. .. code-block:: python (1, (2, 3), 4) -> (1, 2, 3, 4) """ for item in sequence: if hasattr(item, "__iter__") and not isinstance(item, str) and not isinstance(item, bytes): ...
Runs the job by invoking the command from the given arglist. Finds tracking urls from the output and attempts to fetch errors using those urls if the job fails. Throws HadoopJobError with information about the error ( including stdout and stderr from the process ) on failure and returns normally otherwise.
def run_and_track_hadoop_job(arglist, tracking_url_callback=None, env=None): """ Runs the job by invoking the command from the given arglist. Finds tracking urls from the output and attempts to fetch errors using those urls if the job fails. Throws HadoopJobError with information about the error (in...
Uses mechanize to fetch the actual task logs from the task tracker.
def fetch_task_failures(tracking_url): """ Uses mechanize to fetch the actual task logs from the task tracker. This is highly opportunistic, and we might not succeed. So we set a low timeout and hope it works. If it does not, it's not the end of the world. TODO: Yarn has a REST API that we sho...
Protected method
def _get_pool(self): """ Protected method """ if self.pool: return self.pool if hadoop().pool: return hadoop().pool
Get the MapReduce runner for this job.
def job_runner(self): # We recommend that you define a subclass, override this method and set up your own config """ Get the MapReduce runner for this job. If all outputs are HdfsTargets, the DefaultHadoopJobRunner will be used. Otherwise, the LocalJobRunner which streams all da...
Writer format is a method which iterates over the output records from the reducer and formats them for output.
def writer(self, outputs, stdout, stderr=sys.stderr): """ Writer format is a method which iterates over the output records from the reducer and formats them for output. The default implementation outputs tab separated items. """ for output in outputs: try: ...
Increments a Hadoop counter.
def incr_counter(self, *args, **kwargs): """ Increments a Hadoop counter. Since counters can be a bit slow to update, this batches the updates. """ threshold = kwargs.get("threshold", self.batch_counter_default) if len(args) == 2: # backwards compatibility wi...
Increments any unflushed counter values.
def _flush_batch_incr_counter(self): """ Increments any unflushed counter values. """ for key, count in six.iteritems(self._counter_dict): if count == 0: continue args = list(key) + [count] self._incr_counter(*args) self._co...
Increments a Hadoop counter.
def _incr_counter(self, *args): """ Increments a Hadoop counter. Note that this seems to be a bit slow, ~1 ms Don't overuse this function by updating very frequently. """ if len(args) == 2: # backwards compatibility with existing hadoop jobs grou...
Dump instance to file.
def dump(self, directory=''): """ Dump instance to file. """ with self.no_unpicklable_properties(): file_name = os.path.join(directory, 'job-instance.pickle') if self.__module__ == '__main__': d = pickle.dumps(self) module_name = os...
Iterate over input and call the mapper for each item. If the job has a parser defined the return values from the parser will be passed as arguments to the mapper.
def _map_input(self, input_stream): """ Iterate over input and call the mapper for each item. If the job has a parser defined, the return values from the parser will be passed as arguments to the mapper. If the input is coded output from a previous run, the arguments wil...
Iterate over input collect values with the same key and call the reducer for each unique key.
def _reduce_input(self, inputs, reducer, final=NotImplemented): """ Iterate over input, collect values with the same key, and call the reducer for each unique key. """ for key, values in groupby(inputs, key=lambda x: self.internal_serialize(x[0])): for output in reducer(self....
Run the mapper on the hadoop node.
def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout): """ Run the mapper on the hadoop node. """ self.init_hadoop() self.init_mapper() outputs = self._map_input((line[:-1] for line in stdin)) if self.reducer == NotImplemented: self.writer(outputs, ...
Run the reducer on the hadoop node.
def run_reducer(self, stdin=sys.stdin, stdout=sys.stdout): """ Run the reducer on the hadoop node. """ self.init_hadoop() self.init_reducer() outputs = self._reduce_input(self.internal_reader((line[:-1] for line in stdin)), self.reducer, self.final_reducer) self.w...
Reader which uses python eval on each part of a tab separated string. Yields a tuple of python objects.
def internal_reader(self, input_stream): """ Reader which uses python eval on each part of a tab separated string. Yields a tuple of python objects. """ for input_line in input_stream: yield list(map(self.deserialize, input_line.split("\t")))
Writer which outputs the python repr for each item.
def internal_writer(self, outputs, stdout): """ Writer which outputs the python repr for each item. """ for output in outputs: print("\t".join(map(self.internal_serialize, output)), file=stdout)
Mark this update as complete.
def touch(self, connection=None): """ Mark this update as complete. Important: If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() i...
Get a psycopg2 connection object to the database where the table is.
def connect(self): """ Get a psycopg2 connection object to the database where the table is. """ connection = psycopg2.connect( host=self.host, port=self.port, database=self.database, user=self.user, password=self.password) ...
Create marker table if it doesn t exist.
def create_marker_table(self): """ Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset. """ connection = self.connect() connection.autocommit = True cursor = connection.cursor() if self.use_db_...
Return/ yield tuples or lists corresponding to each row to be inserted.
def rows(self): """ Return/yield tuples or lists corresponding to each row to be inserted. """ with self.input().open('r') as fobj: for line in fobj: yield line.strip('\n').split('\t')
Applied to each column of every row returned by rows.
def map_column(self, value): """ Applied to each column of every row returned by `rows`. Default behaviour is to escape special characters and identify any self.null_values. """ if value in self.null_values: return r'\\N' else: return default_esca...
Returns a PostgresTarget representing the inserted dataset.
def output(self): """ Returns a PostgresTarget representing the inserted dataset. Normally you don't override this. """ return PostgresTarget( host=self.host, database=self.database, user=self.user, password=self.password, ...
Inserts data generated by rows () into target table.
def run(self): """ Inserts data generated by rows() into target table. If the target table doesn't exist, self.create_table will be called to attempt to create the table. Normally you don't want to override this. """ if not (self.table and self.columns): rai...
Get configs singleton for parser
def get_config(parser=PARSER): """Get configs singleton for parser """ parser_class = PARSERS[parser] _check_parser(parser_class, parser) return parser_class.instance()
Select config parser by file extension and add path into parser.
def add_config_path(path): """Select config parser by file extension and add path into parser. """ if not os.path.isfile(path): warnings.warn("Config file does not exist: {path}".format(path=path)) return False # select parser by file extension _base, ext = os.path.splitext(path) ...
This method compresses and uploads packages to the cluster
def _setup_packages(self, sc): """ This method compresses and uploads packages to the cluster """ packages = self.py_packages if not packages: return for package in packages: mod = importlib.import_module(package) try: ...
Run either the mapper combiner or reducer from the class instance in the file job - instance. pickle.
def main(args=None, stdin=sys.stdin, stdout=sys.stdout, print_exception=print_exception): """ Run either the mapper, combiner, or reducer from the class instance in the file "job-instance.pickle". Arguments: kind -- is either map, combiner, or reduce """ try: # Set up logging. ...
Run luigi with command line parsing but raise SystemExit with the configured exit code.
def run_with_retcodes(argv): """ Run luigi with command line parsing, but raise ``SystemExit`` with the configured exit code. Note: Usually you use the luigi binary directly and don't call this function yourself. :param argv: Should (conceptually) be ``sys.argv[1:]`` """ logger = logging.getLo...
Finds all tasks on all paths from provided CLI task
def find_deps_cli(): ''' Finds all tasks on all paths from provided CLI task ''' cmdline_args = sys.argv[1:] with CmdlineParser.global_instance(cmdline_args) as cp: return find_deps(cp.get_task_obj(), upstream().family)
Returns a task s output as a string
def get_task_output_description(task_output): ''' Returns a task's output as a string ''' output_description = "n/a" if isinstance(task_output, RemoteTarget): output_description = "[SSH] {0}:{1}".format(task_output._fs.remote_context.host, task_output.path) elif isinstance(task_output, ...
Tweaks glob into a list of more specific globs that together still cover paths and not too much extra.
def _constrain_glob(glob, paths, limit=5): """ Tweaks glob into a list of more specific globs that together still cover paths and not too much extra. Saves us minutes long listings for long dataset histories. Specifically, in this implementation the leftmost occurrences of "[0-9]" give rise to a f...
Wanted functionality from Counters ( new in Python 2. 7 ).
def most_common(items): """ Wanted functionality from Counters (new in Python 2.7). """ counts = {} for i in items: counts.setdefault(i, 0) counts[i] += 1 return max(six.iteritems(counts), key=operator.itemgetter(1))
Builds a glob listing existing output paths.
def _get_per_location_glob(tasks, outputs, regexes): """ Builds a glob listing existing output paths. Esoteric reverse engineering, but worth it given that (compared to an equivalent contiguousness guarantee by naive complete() checks) requests to the filesystem are cut by orders of magnitude, and ...
Yields a ( filesystem glob ) tuple per every output location of task.
def _get_filesystems_and_globs(datetime_to_task, datetime_to_re): """ Yields a (filesystem, glob) tuple per every output location of task. The task can have one or several FileSystemTarget outputs. For convenience, the task can be a luigi.WrapperTask, in which case outputs of all its dependencies ...
Get all the paths that do in fact exist. Returns a set of all existing paths.
def _list_existing(filesystem, glob, paths): """ Get all the paths that do in fact exist. Returns a set of all existing paths. Takes a luigi.target.FileSystem object, a str which represents a glob and a list of strings representing paths. """ globs = _constrain_glob(glob, paths) time_start ...
Efficiently determines missing datetimes by filesystem listing.
def infer_bulk_complete_from_fs(datetimes, datetime_to_task, datetime_to_re): """ Efficiently determines missing datetimes by filesystem listing. The current implementation works for the common case of a task writing output to a ``FileSystemTarget`` whose path is built using strftime with format li...
DONT USE. Will be deleted soon. Use self. of !
def of_cls(self): """ DONT USE. Will be deleted soon. Use ``self.of``! """ if isinstance(self.of, six.string_types): warnings.warn('When using Range programatically, dont pass "of" param as string!') return Register.get_task_cls(self.of) return self.of
For consistent metrics one should consider the entire range but it is open ( infinite ) if stop or start is None.
def _emit_metrics(self, missing_datetimes, finite_start, finite_stop): """ For consistent metrics one should consider the entire range, but it is open (infinite) if stop or start is None. Hence make do with metrics respective to the finite simplification. """ datetimes =...
Override in subclasses to do bulk checks.
def missing_datetimes(self, finite_datetimes): """ Override in subclasses to do bulk checks. Returns a sorted list. This is a conservative base implementation that brutally checks completeness, instance by instance. Inadvisable as it may be slow. """ return [d ...
Backward compatible wrapper. Will be deleted eventually ( stated on Dec 2015 )
def _missing_datetimes(self, finite_datetimes): """ Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015) """ try: return self.missing_datetimes(finite_datetimes) except TypeError as ex: if 'missing_datetimes()' in repr(ex): ...
Given a dictionary of parameters will extract the ranged task parameter value
def parameters_to_datetime(self, p): """ Given a dictionary of parameters, will extract the ranged task parameter value """ dt = p[self._param_name] return datetime(dt.year, dt.month, dt.day)
Simply returns the points in time that correspond to turn of day.
def finite_datetimes(self, finite_start, finite_stop): """ Simply returns the points in time that correspond to turn of day. """ date_start = datetime(finite_start.year, finite_start.month, finite_start.day) dates = [] for i in itertools.count(): t = date_star...
Simply returns the points in time that correspond to whole hours.
def finite_datetimes(self, finite_start, finite_stop): """ Simply returns the points in time that correspond to whole hours. """ datehour_start = datetime(finite_start.year, finite_start.month, finite_start.day, finite_start.hour) datehours = [] for i in itertools.count()...
Simply returns the points in time that correspond to a whole number of minutes intervals.
def finite_datetimes(self, finite_start, finite_stop): """ Simply returns the points in time that correspond to a whole number of minutes intervals. """ # Validate that the minutes_interval can divide 60 and it is greater than 0 and lesser than 60 if not (0 < self.minutes_interva...
Simply returns the points in time that correspond to turn of month.
def finite_datetimes(self, finite_start, finite_stop): """ Simply returns the points in time that correspond to turn of month. """ start_date = self._align(finite_start) aligned_stop = self._align(finite_stop) dates = [] for m in itertools.count(): t =...
Mark this update as complete.
def touch(self, connection=None): """ Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() i...
Create a SQL Server connection and return a connection object
def connect(self): """ Create a SQL Server connection and return a connection object """ connection = _mssql.connect(user=self.user, password=self.password, server=self.host, port=...
Create marker table if it doesn t exist. Use a separate connection since the transaction might have to be reset.
def create_marker_table(self): """ Create marker table if it doesn't exist. Use a separate connection since the transaction might have to be reset. """ connection = self.connect() try: connection.execute_non_query( """ CREATE TABLE {marker_tabl...
Retrieve an opener for the given protocol
def get_opener(self, name): """Retrieve an opener for the given protocol :param name: name of the opener to open :type name: string :raises NoOpenerError: if no opener has been registered of that name """ if name not in self.registry: raise NoOpenerError("No...
Adds an opener to the registry
def add(self, opener): """Adds an opener to the registry :param opener: Opener object :type opener: Opener inherited object """ index = len(self.openers) self.openers[index] = opener for name in opener.names: self.registry[name] = index
Open target uri.
def open(self, target_uri, **kwargs): """Open target uri. :param target_uri: Uri to open :type target_uri: string :returns: Target object """ target = urlsplit(target_uri, scheme=self.default_opener) opener = self.get_opener(target.scheme) query = open...
Converts the query string from a target uri uses cls. allowed_kwargs and cls. filter_kwargs to drive logic.
def conform_query(cls, query): """Converts the query string from a target uri, uses cls.allowed_kwargs, and cls.filter_kwargs to drive logic. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls...
Override this method to use values from the parsed uri to initialize the expected target.
def get_target(cls, scheme, path, fragment, username, password, hostname, port, query, **kwargs): """Override this method to use values from the parsed uri to initialize the expected target. """ raise NotImplementedError("get_target must be overridden")
: param tasks:: param worker_scheduler_factory:: param override_defaults:: return: True if all tasks and their dependencies were successfully run ( or already completed ) ; False if any error occurred. It will return a detailed response of type LuigiRunResult instead of a boolean if detailed_summary = True.
def _schedule_and_run(tasks, worker_scheduler_factory=None, override_defaults=None): """ :param tasks: :param worker_scheduler_factory: :param override_defaults: :return: True if all tasks and their dependencies were successfully run (or already completed); False if any error occurred. ...
Please dont use. Instead use luigi binary.
def run(*args, **kwargs): """ Please dont use. Instead use `luigi` binary. Run from cmdline using argparse. :param use_dynamic_argparse: Deprecated and ignored """ luigi_run_result = _run(*args, **kwargs) return luigi_run_result if kwargs.get('detailed_summary') else luigi_run_result.sched...
Run internally bypassing the cmdline parsing.
def build(tasks, worker_scheduler_factory=None, detailed_summary=False, **env_params): """ Run internally, bypassing the cmdline parsing. Useful if you have some luigi code that you want to run internally. Example: .. code-block:: python luigi.build([MyTask1(), MyTask2()], local_scheduler...
Mark this update as complete.
def touch(self, connection=None): """ Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() i...
Create marker table if it doesn t exist.
def create_marker_table(self): """ Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset. """ connection = self.connect(autocommit=True) cursor = connection.cursor() try: cursor.execute( ...
Inserts data generated by rows () into target table.
def run(self): """ Inserts data generated by rows() into target table. If the target table doesn't exist, self.create_table will be called to attempt to create the table. Normally you don't want to override this. """ if not (self.table and self.columns): rai...
Coerce input arguments to use temporary files when used for output.
def fix_paths(job): """ Coerce input arguments to use temporary files when used for output. Return a list of temporary file pairs (tmpfile, destination path) and a list of arguments. Converts each HdfsTarget to a string for the path. """ tmp_files = [] args = [] for x in job.args()...
Get name of first active job queue
def get_active_queue(self): """Get name of first active job queue""" # Get dict of active queues keyed by name queues = {q['jobQueueName']: q for q in self._client.describe_job_queues()['jobQueues'] if q['state'] == 'ENABLED' and q['status'] == 'VALID'} if not queues: ...
Retrieve the first job ID matching the given name
def get_job_id_from_name(self, job_name): """Retrieve the first job ID matching the given name""" jobs = self._client.list_jobs(jobQueue=self._queue, jobStatus='RUNNING')['jobSummaryList'] matching_jobs = [job for job in jobs if job['jobName'] == job_name] if matching_jobs: r...
Retrieve task statuses from ECS API
def get_job_status(self, job_id): """Retrieve task statuses from ECS API :param job_id (str): AWS Batch job uuid Returns one of {SUBMITTED|PENDING|RUNNABLE|STARTING|RUNNING|SUCCEEDED|FAILED} """ response = self._client.describe_jobs(jobs=[job_id]) # Error checking ...
Retrieve log stream from CloudWatch
def get_logs(self, log_stream_name, get_last=50): """Retrieve log stream from CloudWatch""" response = self._log_client.get_log_events( logGroupName='/aws/batch/job', logStreamName=log_stream_name, startFromHead=False) events = response['events'] retur...
Wrap submit_job with useful defaults
def submit_job(self, job_definition, parameters, job_name=None, queue=None): """Wrap submit_job with useful defaults""" if job_name is None: job_name = _random_id() response = self._client.submit_job( jobName=job_name, jobQueue=queue or self.get_active_queue()...
Poll task status until STOPPED
def wait_on_job(self, job_id): """Poll task status until STOPPED""" while True: status = self.get_job_status(job_id) if status == 'SUCCEEDED': logger.info('Batch job {} SUCCEEDED'.format(job_id)) return True elif status == 'FAILED': ...
Register a job definition with AWS Batch using a JSON
def register_job_definition(self, json_fpath): """Register a job definition with AWS Batch, using a JSON""" with open(json_fpath) as f: job_def = json.load(f) response = self._client.register_job_definition(**job_def) status_code = response['ResponseMetadata']['HTTPStatusCode...