code stringlengths 1 18.2k |
|---|
def new_from_bundle_config(self, config): """ Create a new bundle, or link to an existing one, based on the identity in config data. :param config: A Dict form of a bundle.yaml file :return: """ identity = Identity.from_dict(config['identity']) ds = self._db.dataset(identity.vid, exception=False) if not ds: ds = self._... |
def bundle(self, ref, capture_exceptions=False): """Return a bundle build on a dataset, with the given vid or id reference""" from ..orm.exc import NotFoundError if isinstance(ref, Dataset): ds = ref else: try: ds = self._db.dataset(ref) except NotFoundError: ds = None if not ds: try: p = self.partition(ref) ds = p._bu... |
def partition(self, ref, localize=False): """ Finds partition by ref and converts to bundle partition. :param ref: A partition reference :param localize: If True, copy a remote partition to local filesystem. Defaults to False :raises: NotFoundError: if partition with given ref not found. :return: orm.Partition: found p... |
if not p: raise NotFoundError("No partition for ref: '{}'".format(ref)) b = self.bundle(p.d_vid) p = b.wrap_partition(p) if localize: p.localize() return p |
def table(self, ref): """ Finds table by ref and returns it. Args: ref (str): id, vid (versioned id) or name of the table Raises: NotFoundError: if table with given ref not found. Returns: orm.Table """ try: obj_number = ObjectNumber.parse(ref) ds_obj_number = obj_number.as_dataset dataset = self._db.dataset(ds_obj_num... |
def remove(self, bundle): """ Removes a bundle from the library and deletes the configuration for it from the library database.""" from six import string_types if isinstance(bundle, string_types): bundle = self.bundle(bundle) self.database.remove_dataset(bundle.dataset) |
def duplicate(self, b): """Duplicate a bundle, with a higher version number. This only copies the files, under the theory that the bundle can be rebuilt from them. """ on = b.identity.on on.revision = on.revision + 1 try: extant = self.bundle(str(on)) if extant: raise ConflictError('Already have a bundle with vid: {}'.... |
return nb |
def checkin_bundle(self, db_path, replace=True, cb=None): """Add a bundle, as a Sqlite file, to this library""" from ambry.orm.exc import NotFoundError db = Database('sqlite:///{}'.format(db_path)) db.open() if len(db.datasets) == 0: raise NotFoundError("Did not get a dataset in the {} bundle".format(db_path)) ds = db.... |
def send_to_remote(self, b, no_partitions=False): """ Copy a bundle to a new Sqlite file, then store the file on the remote. :param b: The bundle :return: """ raise DeprecationWarning("Don't use any more?") from ambry.bundle.process import call_interval remote_name = self.resolve_remote(b) remote = self.remote(remote_n... |
partition'.format(p.identity.vname), item_count=total[0]) remote.makedir(os.path.dirname(p.datafile.path), recursive=True, allow_recreate=True) event = remote.setcontents_async(p.datafile.path, fin, progress_callback=progress) event.wait() ps.update(state='done') ps.add(message='Setting metadata') ident = json.dumps(b.... |
def checkin_remote_bundle(self, ref, remote=None): """ Checkin a remote bundle to this library. :param ref: Any bundle reference :param remote: If specified, use this remote. If not, search for the reference in cached directory listings :param cb: A one argument progress callback :return: """ if not remote: remote, vna... |
def _checkin_remote_bundle(self, remote, ref): """ Checkin a remote bundle from a remote :param remote: a Remote object :param ref: Any bundle reference :return: The vid of the loaded bundle """ from ambry.bundle.process import call_interval from ambry.orm.exc import NotFoundError from ambry.orm import Remote from ambr... |
now. b.dataset.data['remote_name'] = remote.short_name b.dataset.upstream = remote.url b.dstate = b.STATES.CHECKEDOUT b.commit() finally: if b: b.progress.close() vid = b.identity.vid return vid |
def remotes(self): """Return the names and URLs of the remotes""" from ambry.orm import Remote for r in self.database.session.query(Remote).all(): if not r.short_name: continue yield self.remote(r.short_name) |
def _remote(self, name): """Return a remote for which 'name' matches the short_name or url """ from ambry.orm import Remote from sqlalchemy import or_ from ambry.orm.exc import NotFoundError from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound if not name.strip(): raise NotFoundError("Empty remote name") ... |
def _find_remote_bundle(self, ref, remote_service_type='s3'): """ Locate a bundle, by any reference, among the configured remotes. The routine will only look in the cache directory lists stored in the remotes, which must be updated to be current. :param ref: :return: (remote,vname) or (None,None) if the ref is not foun... |
def find_remote_bundle(self, ref, try_harder=None): """ Locate a bundle, by any reference, among the configured remotes. The routine will only look in the cache directory lists stored in the remotes, which must be updated to be current. :param vid: A bundle or partition reference, vid, or name :param try_harder: If the... |
if remote: return (remote, vid) return (None, None) |
def account(self, url): """ Return accounts references for the given account id. :param account_id: :param accounts_password: The password for decrypting the secret :return: """ from sqlalchemy.orm.exc import NoResultFound from ambry.orm.exc import NotFoundError from ambry.util import parse_url_to_dict from ambry.orm i... |
def accounts(self): """ Return an account reference :param account_id: :param accounts_password: The password for decrypting the secret :return: """ d = {} if False and not self._account_password: from ambry.dbexceptions import ConfigurationError raise ConfigurationError( "Can't access accounts without setting an accou... |
def number(self, assignment_class=None, namespace='d'): """ Return a new number. :param assignment_class: Determines the length of the number. Possible values are 'authority' (3 characters) , 'registered' (5) , 'unregistered' (7) and 'self' (9). Self assigned numbers are random and acquired locally, while the other ass... |
missing configuration is equivalent to 'self' self.logger.error('No number server configuration; returning self assigned number') return str(DatasetNumber()) for assignment_class in ('self', 'unregistered', 'registered', 'authority'): if assignment_class+'-key' in nsconfig: break # For the case where the number configu... |
'but they are longer than centrally generated numbers.') n = str(DatasetNumber()) return n |
def edit_history(self): """Return config record information about the most recent bundle accesses and operations""" ret = self._db.session\ .query(Config)\ .filter(Config.type == 'buildstate')\ .filter(Config.group == 'access')\ .filter(Config.key == 'last')\ .order_by(Config.modified.desc())\ .all() return ret |
def import_bundles(self, dir, detach=False, force=False): """ Import bundles from a directory :param dir: :return: """ import yaml fs = fsopendir(dir) bundles = [] for f in fs.walkfiles(wildcard='bundle.yaml'): self.logger.info('Visiting {}'.format(f)) config = yaml.load(fs.getcontents(f)) if not config: self.logger.er... |
def process_pool(self, limited_run=False): """Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value""" from multiprocessing import cpu_count from ambry.bundle.concurrent import Pool, init_library if self.processes: cpus = self.processes else: cpus = cpu_count() self.logger... |
def file_loc(): """Return file and line number""" import sys import inspect try: raise Exception except: file_ = '.../' + '/'.join((inspect.currentframe().f_code.co_filename.split('/'))[-3:]) line_ = sys.exc_info()[2].tb_frame.f_back.f_lineno return "{}:{}".format(file_, line_) |
def make_row_processors(bundle, source_headers, dest_table, env): """ Make multiple row processors for all of the columns in a table. :param source_headers: :return: """ dest_headers = [c.name for c in dest_table.columns] row_processors = [] out = [file_header] transforms = list(dest_table.transforms) column_names = []... |
i_s = source_headers.index(column.name) header_s = column.name v = 'row[{}]'.format(i_s) except ValueError as e: i_s = 'None' header_s = None v = 'None' if col_num > 1 else 'row_n' # Give the id column the row number i_d = column.sequence_id - 1 header_d = column.name template_args = dict( f_name=f_name, table_name=des... |
Add the final datatype cast, which is done seperately to avoid an unecessary function call. stack = '\n'.join("{}cast_{}(row[{}], '{}', errors),".format(indent, c.datatype, i, c.name) for i, c in enumerate(dest_table.columns) ) out.append(row_template.format( table=dest_table.name, stage=len(transforms), stack=stack ))... |
def calling_code(f, f_name=None, raise_for_missing=True): """Return the code string for calling a function. """ import inspect from ambry.dbexceptions import ConfigurationError if inspect.isclass(f): try: args = inspect.getargspec(f.__init__).args except TypeError as e: raise TypeError("Failed to inspect {}: {}".format... |
def make_stack(env, stage, segment): """For each transform segment, create the code in the try/except block with the assignements for pipes in the segment """ import string import random from ambry.valuetype import ValueType column = segment['column'] def make_line(column, t): preamble = [] line_t = "v = {} # {}" if is... |
stage, rnd) try: a, b, fl = rewrite_tg(env, name, t) except CodeGenError as e: raise CodeGenError("Failed to re-write pipe code '{}' in column '{}.{}': {} " .format(t, column.table.name, column.name, e)) cc = str(a) if b: preamble.append("{} = {} # {}".format(name, b, fl)) line = line_t.format(cc, fl) return line, prea... |
def rewrite_tg(env, tg_name, code): """Re-write a transform generating function pipe specification by extracting the tranform generating part, and replacing it with the generated transform. so: tgen(a,b,c).foo.bar becomes: tg = tgen(a,b,c) tg.foo.bar """ visitor = ReplaceTG(env, tg_name) assert visitor.tg_name tree = v... |
def push(self, el): """ Put a new element in the queue. """ count = next(self.counter) heapq.heappush(self._queue, (el, count)) |
def geo_description(self): """Return a description of the geographic extents, using the largest scale space and grain coverages""" sc = self._p.space_coverage gc = self._p.grain_coverage if sc and gc: if parse_to_gvid(gc[0]).level == 'state' and parse_to_gvid(sc[0]).level == 'state': return parse_to_gvid(sc[0]).geo_nam... |
def time_description(self): """String description of the year or year range""" tc = [t for t in self._p.time_coverage if t] if not tc: return '' mn = min(tc) mx = max(tc) if not mn and not mx: return '' elif mn == mx: return mn else: return "{} to {}".format(mn, mx) |
def sub_description(self): """Time and space dscription""" gd = self.geo_description td = self.time_description if gd and td: return '{}, {}. {} Rows.'.format(gd, td, self._p.count) elif gd: return '{}. {} Rows.'.format(gd, self._p.count) elif td: return '{}. {} Rows.'.format(td, self._p.count) else: return '{} Rows.'.... |
def identity(self): """Return this partition information as a PartitionId.""" if self.dataset is None: # The relationship will be null until the object is committed s = object_session(self) ds = s.query(Dataset).filter(Dataset.id_ == self.d_id).one() else: ds = self.dataset d = { 'id': self.id, 'vid': self.vid, 'name':... |
def set_coverage(self, stats): """"Extract time space and grain coverage from the stats and store them in the partition""" from ambry.util.datestimes import expand_to_years scov = set() tcov = set() grains = set() def summarize_maybe(gvid): try: return parse_to_gvid(gvid).summarize() except: return None def simplifiy_m... |
for x in simplifiy_maybe(stats[c.name].uniques, c)) grains |= set(summarize_maybe(gvid) for gvid in stats[c.name].uniques) elif stats[c.name].is_year: tcov |= set(int_maybe(x) for x in stats[c.name].uniques) elif stats[c.name].is_date: # The fuzzy=True argument allows ignoring the '-' char in dates produced by .isoform... |
in scov if bool(x) and x.sl in (10, 40, 50, 60, 160, 400)]) # # Time Coverage # From the source # If there was a time value in the source that this partition was created from, then # add it to the years. if 'source_data' in self.data: for source_name, source in list(self.data['source_data'].items()): if 'time' in sourc... |
def detail_dict(self): """A more detailed dict that includes the descriptions, sub descriptions, table and columns.""" d = self.dict def aug_col(c): d = c.dict d['stats'] = [s.dict for s in c.stats] return d d['table'] = self.table.dict d['table']['columns'] = [aug_col(c) for c in self.table.columns] return d |
def local_datafile(self): """Return the datafile for this partition, from the build directory, the remote, or the warehouse""" from ambry_sources import MPRowsFile from fs.errors import ResourceNotFoundError from ambry.orm.exc import NotFoundError try: return MPRowsFile(self._bundle.build_fs, self.cache_key) except Res... |
def remote(self): """ Return the remote for this partition :return: """ from ambry.exc import NotFoundError ds = self.dataset if 'remote_name' not in ds.data: raise NotFoundError('Could not determine remote for partition: {}'.format(self.identity.fqname)) return self._bundle.library.remote(ds.data['remote_name']) |
def is_local(self): """Return true is the partition file is local""" from ambry.orm.exc import NotFoundError try: if self.local_datafile.exists: return True except NotFoundError: pass return False |
def localize(self, ps=None): """Copy a non-local partition file to the local build directory""" from filelock import FileLock from ambry.util import ensure_dir_exists from ambry_sources import MPRowsFile from fs.errors import ResourceNotFoundError if self.is_local: return local = self._bundle.build_fs b = self._bundle.... |
with remote ( http) API, only FS ( s3:, file:) if self.is_local: return self try: with remote.fs.open(self.cache_key + MPRowsFile.EXTENSION, 'rb') as f: event = local.setcontents_async(self.cache_key + MPRowsFile.EXTENSION, f, progress_callback=progress, error_callback=exception_cb) event.wait() if ps: ps.update_done()... |
def reader(self): from ambry.orm.exc import NotFoundError from fs.errors import ResourceNotFoundError """The reader for the datafile""" try: return self.datafile.reader except ResourceNotFoundError: raise NotFoundError("Failed to find partition file, '{}' " .format(self.datafile.path)) |
def select(self, predicate=None, headers=None): """ Select rows from the reader using a predicate to select rows and and itemgetter to return a subset of elements :param predicate: If defined, a callable that is called for each row, and if it returns true, the row is included in the output. :param headers: If defined, ... |
a getter that extracts the inner row, or which converts the RowProxy to a dict: list(s.datafile.select(lambda r: r.stusab == 'CA', lambda r: r.dict )) """ # FIXME; in Python 3, use yield from with self.reader as r: for row in r.select(predicate, headers): yield row |
def analysis(self): """Return an AnalysisPartition proxy, which wraps this partition to provide acess to dataframes, shapely shapes and other analysis services""" if isinstance(self, PartitionProxy): return AnalysisPartition(self._obj) else: return AnalysisPartition(self) |
def measuredim(self): """Return a MeasureDimension proxy, which wraps the partition to provide access to columns in terms of measures and dimensions""" if isinstance(self, PartitionProxy): return MeasureDimensionPartition(self._obj) else: return MeasureDimensionPartition(self) |
def update_id(self, sequence_id=None): """Alter the sequence id, and all of the names and ids derived from it. This often needs to be done after an IntegrityError in a multiprocessing run""" if sequence_id: self.sequence_id = sequence_id self._set_ids(force=True) if self.dataset: self._update_names() |
def _update_names(self): """Update the derived names""" d = dict( table=self.table_name, time=self.time, space=self.space, grain=self.grain, variant=self.variant, segment=self.segment ) assert self.dataset name = PartialPartitionName(**d).promote(self.dataset.identity.name) self.name = str(name.name) self.vname = str(n... |
def before_insert(mapper, conn, target): """event.listen method for Sqlalchemy to set the sequence for this object and create an ObjectNumber value for the id_""" target._set_ids() if target.name and target.vname and target.cache_key and target.fqname and not target.dataset: return Partition.before_update(mapper, conn,... |
def dataframe(self, predicate=None, filtered_columns=None, columns=None, df_class=None): """Return the partition as a Pandas dataframe :param predicate: If defined, a callable that is called for each row, and if it returns true, the row is included in the output. :param filtered_columns: If defined, the value is a dict... |
string_types): return '"{}"'.format(v) else: return v code = ' and '.join("row.{} == {}".format(k, maybe_quote(v)) for k, v in filtered_columns.items()) predicate = eval('lambda row: {}'.format(code)) if predicate: def yielder(): for row in self.reader: if predicate(row): if ig: yield ig(row) else: yield row.dict df = ... |
def shapes(self, simplify=None, predicate=None): """ Return geodata as a list of Shapely shapes :param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry. :param predicate: A single-argument function to select which records to include in the output. :return: A list of Shapely ... |
def patches(self, basemap, simplify=None, predicate=None, args_f=None, **kwargs): """ Return geodata as a list of Matplotlib patches :param basemap: A mpl_toolkits.basemap.Basemap :param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry. :param predicate: A single-argument fu... |
**args) def yield_patches(row): if simplify: shape = loads(row.geometry).simplify(simplify) else: shape = loads(row.geometry) if shape.geom_type == 'MultiPolygon': for subshape in shape.geoms: yield make_patch(subshape, row) else: yield make_patch(shape, row) return [patch for row in self if predicate(row) for patch in... |
def measures(self): """Iterate over all measures""" from ambry.valuetype.core import ROLE return [c for c in self.columns if c.role == ROLE.MEASURE] |
def measure(self, vid): """Return a measure, given its vid or another reference""" from ambry.orm import Column if isinstance(vid, PartitionColumn): return vid elif isinstance(vid, Column): return PartitionColumn(vid) else: return PartitionColumn(self.table.column(vid), self) |
def dataframe(self, measure, p_dim, s_dim=None, filters={}, df_class=None): """ Return a dataframe with a sumse of the columns of the partition, including a measure and one or two dimensions. FOr dimensions that have labels, the labels are included The returned dataframe will have extra properties to describe the conve... |
:param s_dim: a secondary dimension. The returned frame will be unstacked on this dimension :param filters: A dict of column names, mapped to a column value, indicating rows to select. a row that passes the filter must have the values for all given rows; the entries are ANDED :param df_class: :return: a Dataframe, with... |
k, v in filters.items(): if isinstance(v, dict): # The filter is actually the whole set of possible options, so # just select the first one v = v.keys()[0] selected_filters.append("row.{} == {}".format(k, maybe_quote(v))) code = ' and '.join(selected_filters) predicate = eval('lambda row: {}'.format(code)) else: code =... |
s_dim.name): continue # FIXME! This will only work if the child is only level from the parent. Should # have an acessor for the top level. if c.parent and (c.parent == p_dim.name or (s_dim and c.parent == s_dim.name)): continue if c.is_measure: agg[c.name] = np.mean if c.is_dimension: agg[c.name] = aggregate_string plo... |
list(t) # Really should not do this, but I don't want to re-build the dataframe with another # class df.__class__.rows = property(rows) return df |
def dimension_set(self, p_dim, s_dim=None, dimensions=None, extant=set()): """ Return a dict that describes the combination of one or two dimensions, for a plot :param p_dim: :param s_dim: :param dimensions: :param extant: :return: """ if not dimensions: dimensions = self.primary_dimensions key = p_dim.name if s_dim: k... |
value_type = 'time' chart_type = 'line' elif p_dim.valuetype_class.is_geo(): value_type = 'geo' chart_type = 'map' else: value_type = 'general' chart_type = 'bar' return dict( key=key, p_dim=p_dim.name, p_dim_type=value_type, p_label=p_dim.label_or_self.name, s_dim=s_dim.name if s_dim else None, s_label=s_dim.label_or_... |
def label(self): """"Return first child that of the column that is marked as a label""" for c in self.table.columns: if c.parent == self.name and 'label' in c.valuetype: return PartitionColumn(c, self._partition) |
def value_labels(self): """Return a map of column code values mapped to labels, for columns that have a label column If the column is not assocaited with a label column, it returns an identity map. WARNING! This reads the whole partition, so it is really slow """ from operator import itemgetter card = self.pstats.nuniq... |
def list_build_configuration_sets(page_size=200, page_index=0, sort="", q=""): """ List all build configuration sets """ data = list_build_configuration_sets_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data) |
def create_build_configuration_set_raw(**kwargs): """ Create a new BuildConfigurationSet. """ config_set = _create_build_config_set_object(**kwargs) response = utils.checked_api_call(pnc_api.build_group_configs, 'create_new', body=config_set) if response: return response.content |
def get_build_configuration_set_raw(id=None, name=None): """ Get a specific BuildConfigurationSet by name or ID """ found_id = common.set_id(pnc_api.build_group_configs, id, name) response = utils.checked_api_call(pnc_api.build_group_configs, 'get_specific', id=found_id) if response: return response.content |
def get_build_configuration_set(id=None, name=None): """ Get a specific BuildConfigurationSet by name or ID """ content = get_build_configuration_set_raw(id, name) if content: return utils.format_json(content) |
def update_build_configuration_set(id, **kwargs): """ Update a BuildConfigurationSet """ data = update_build_configuration_set_raw(id, **kwargs) if data: return utils.format_json(data) |
def build_set_raw(id=None, name=None, tempbuild=False, timestamp_alignment=False, force=False, rebuild_mode=common.REBUILD_MODES_DEFAULT, **kwargs): """ Start a build of the given BuildConfigurationSet """ logging.debug("temp_build: " + str(tempbuild)) logging.debug("timestamp_alignment: " + str(timestamp_alignment)) l... |
def build_set(id=None, name=None, temporary_build=False, timestamp_alignment=False, force=False, rebuild_mode=common.REBUILD_MODES_DEFAULT, **kwargs): """ Start a build of the given BuildConfigurationSet """ content = build_set_raw(id, name, temporary_build, timestamp_alignment, force, rebuild_mode, **kwargs) if conten... |
def list_build_configurations_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all build configurations in a given BuildConfigurationSet. """ content = list_build_configurations_for_set_raw(id, name, page_size, page_index, sort, q) if content: return utils.format_json_list(content) |
def add_build_configuration_to_set( set_id=None, set_name=None, config_id=None, config_name=None): """ Add a build configuration to an existing BuildConfigurationSet """ content = add_build_configuration_to_set_raw(set_id, set_name, config_id, config_name) if content: return utils.format_json(content) |
def list_build_records_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all build records for a BuildConfigurationSet """ content = list_build_records_for_set_raw(id, name, page_size, page_index, sort, q) if content: return utils.format_json_list(content) |
def list_build_set_records(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all build set records for a BuildConfigurationSet """ content = list_build_set_records_raw(id, name, page_size, page_index, sort, q) if content: return utils.format_json_list(content) |
def react(reactor, main, argv): """ Call C{main} and run the reactor until the L{Deferred} it returns fires. @param reactor: An unstarted L{IReactorCore} provider which will be run and later stopped. @param main: A callable which returns a L{Deferred}. It should take as many arguments as there are elements in the list ... |
def register_model(cls, ModelClass, form_field=None, widget=None, title=None, prefix=None): """ Register a model to use in the URL field. This function needs to be called once for every model that should be selectable in the URL field. :param ModelClass: The model to register. :param form_field: The form field class us... |
def resolve_objects(cls, objects, skip_cached_urls=False): """ Make sure all AnyUrlValue objects from a set of objects is resolved in bulk. This avoids making a query per item. :param objects: A list or queryset of models. :param skip_cached_urls: Whether to avoid prefetching data that has it's URL cached. """ # Allow ... |
def config(path=None, root=None, db=None): """Return the default run_config object for this installation.""" import ambry.run return ambry.run.load(path=path, root=root, db=db) |
def get_library(path=None, root=None, db=None): import ambry.library as _l """Return the default library for this installation.""" rc = config(path=path, root=root, db=db ) return _l.new_library(rc) |
def doc_parser(): """Utility function to allow getting the arguments for a single command, for Sphinx documentation""" parser = argparse.ArgumentParser( prog='ambry', description='Ambry {}. Management interface for ambry, libraries ' 'and repositories. '.format(ambry._meta.__version__)) return parser |
def get_extra_commands(): """Use the configuration to discover additional CLI packages to load""" from ambry.run import find_config_file from ambry.dbexceptions import ConfigurationError from ambry.util import yaml try: plugins_dir = find_config_file('cli.yaml') except ConfigurationError: return [] with open(plugins_di... |
def _refresh_url(self): """刷新获取 url,失败的时候返回空而不是 None""" songs = self._api.weapi_songs_url([int(self.identifier)]) if songs and songs[0]['url']: self.url = songs[0]['url'] else: self.url = '' |
def url(self): """ We will always check if this song file exists in local library, if true, we return the url of the local file. .. note:: As netease song url will be expired after a period of time, we can not use static url here. Currently, we assume that the expiration time is 20 minutes, after the url expires, it wi... |
def get_handler(progname, fmt=None, datefmt=None, project_id=None, credentials=None, debug_thread_worker=False, **_): """Helper function to create a Stackdriver handler. See `ulogger.stackdriver.CloudLoggingHandlerBuilder` for arguments and supported keyword arguments. Returns: (obj): Instance of `google.cloud.logging.... |
def _get_metadata(self, data_type, key, timeout=5): """Get host instance metadata (only works on GCP hosts). More details about instance metadata: https://cloud.google.com/compute/docs/storing-retrieving-metadata Args: data_type (str): Type of metadata to fetch. Eg. project, instance key (str): Key of metadata to fetch... |
def _create_gcl_resource(self): """Create a configured Resource object. The logging.resource.Resource object enables GCL to filter and bucket incoming logs according to which resource (host) they're coming from. Returns: (obj): Instance of `google.cloud.logging.resource.Resource` """ return gcl_resource.Resource('gce_i... |
def get_formatter(self): """Create a fully configured `logging.Formatter` Example of formatted log message: 2017-08-27T20:19:24.424 cpm-example-gew1 progname (23123): hello Returns: (obj): Instance of `logging.Formatter` """ if not self.fmt: self.fmt = ('%(asctime)s.%(msecs)03d {host} {progname} ' '(%(process)d): %(mes... |
def _set_worker_thread_level(self): """Sets logging level of the background logging thread to DEBUG or INFO """ bthread_logger = logging.getLogger( 'google.cloud.logging.handlers.transports.background_thread') if self.debug_thread_worker: bthread_logger.setLevel(logging.DEBUG) else: bthread_logger.setLevel(logging.INFO... |
def get_handler(self): """Create a fully configured CloudLoggingHandler. Returns: (obj): Instance of `google.cloud.logging.handlers. CloudLoggingHandler` """ gcl_client = gcl_logging.Client( project=self.project_id, credentials=self.credentials) handler = gcl_handlers.CloudLoggingHandler( gcl_client, resource=self.reso... |
def index_dataset(self, dataset, force=False): """ Adds given dataset to the index. """ self.backend.dataset_index.index_one(dataset, force=force) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.