desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Calculate all shard states keys for given mapreduce. Args: mapreduce_state: MapreduceState instance Returns: A list of keys for shard states. The corresponding shard states may not exist.'
@classmethod def calculate_keys_by_mapreduce_state(cls, mapreduce_state):
keys = [] for i in range(mapreduce_state.mapreduce_spec.mapper.shard_count): shard_id = cls.shard_id_from_number(mapreduce_state.key().name(), i) keys.append(cls.get_key_by_shard_id(shard_id)) return keys
'Create new shard state. Args: mapreduce_id: unique mapreduce id as string. shard_number: shard number for which to create shard state. Returns: new instance of ShardState ready to put into datastore.'
@classmethod def create_new(cls, mapreduce_id, shard_number):
shard_id = cls.shard_id_from_number(mapreduce_id, shard_number) state = cls(key_name=shard_id, mapreduce_id=mapreduce_id) return state
'Returns entity kind.'
@classmethod def kind(cls):
return '_GAE_MR_MapreduceControl'
'Retrieves the Key for a mapreduce ID. Args: mapreduce_id: The job to fetch. Returns: Datastore Key for the command for the given job ID.'
@classmethod def get_key_by_job_id(cls, mapreduce_id):
return db.Key.from_path(cls.kind(), ('%s:%s' % (mapreduce_id, cls._KEY_NAME)))
'Causes a job to abort. Args: mapreduce_id: The job to abort. Not verified as a valid job.'
@classmethod def abort(cls, mapreduce_id, **kwargs):
cls(key_name=('%s:%s' % (mapreduce_id, cls._KEY_NAME)), command=cls.ABORT).put(**kwargs)
'Initializes a NamespaceRange instance. Args: namespace_start: A string representing the start of the namespace range. namespace_start is included in the range. If namespace_start is None then the lexographically first namespace is used. namespace_end: A string representing the end of the namespace range. namespace_end...
def __init__(self, namespace_start=None, namespace_end=None, _app=None):
if (namespace_start is None): namespace_start = MIN_NAMESPACE if (namespace_end is None): namespace_end = MAX_NAMESPACE if (namespace_start > namespace_end): raise ValueError(('namespace_start (%r) > namespace_end (%r)' % (namespace_start, namespace_end))) self.__name...
'True if the namespace range only includes a single namespace.'
@property def is_single_namespace(self):
return (self.namespace_start == self.namespace_end)
'Splits the NamespaceRange into two nearly equal-sized ranges. Returns: If this NamespaceRange contains a single namespace then a list containing this NamespaceRange is returned. Otherwise a two-element list containing two NamespaceRanges whose total range is identical to this NamespaceRange\'s is returned.'
def split_range(self):
if self.is_single_namespace: return [self] mid_point = ((_namespace_to_ord(self.namespace_start) + _namespace_to_ord(self.namespace_end)) // 2) return [NamespaceRange(self.namespace_start, _ord_to_namespace(mid_point), _app=self.app), NamespaceRange(_ord_to_namespace((mid_point + 1)), self.namespace...
'Returns a copy of this NamespaceName with a new namespace_start. Args: after_namespace: A namespace string. Returns: A NamespaceRange object whose namespace_start is the lexographically next namespace after the given namespace string. Raises: ValueError: if the NamespaceRange includes only a single namespace.'
def with_start_after(self, after_namespace):
namespace_start = _ord_to_namespace((_namespace_to_ord(after_namespace) + 1)) return NamespaceRange(namespace_start, self.namespace_end, _app=self.app)
'Returns a datastore.Query that generates all namespaces in the range. Returns: A datastore.Query instance that generates db.Keys for each namespace in the NamespaceRange.'
def make_datastore_query(self):
filters = {} filters['__key__ >= '] = _key_for_namespace(self.namespace_start, self.app) filters['__key__ <= '] = _key_for_namespace(self.namespace_end, self.app) return datastore.Query('__namespace__', filters=filters, keys_only=True, _app=self.app)
'Returns a NamespaceRange with leading non-existant namespaces removed. Returns: A copy of this NamespaceRange whose namespace_start is adjusted to exlcude the portion of the range that contains no actual namespaces in the datastore. None is returned if the NamespaceRange contains no actual namespaces in the datastore....
def normalized_start(self):
namespaces_after_key = self.make_datastore_query().Get(1) if (not namespaces_after_key): return None namespace_after_key = (namespaces_after_key[0].name() or '') return NamespaceRange(namespace_after_key, self.namespace_end, _app=self.app)
'Returns a dict representation that can be serialized to JSON.'
def to_json_object(self):
obj_dict = dict(namespace_start=self.namespace_start, namespace_end=self.namespace_end) if (self.app is not None): obj_dict['app'] = self.app return obj_dict
'Returns a NamespaceRange from an object deserialized from JSON.'
@classmethod def from_json_object(cls, json):
return cls(json['namespace_start'], json['namespace_end'], _app=json.get('app'))
'Splits the complete NamespaceRange into n equally-sized NamespaceRanges. Args: n: The maximum number of NamespaceRanges to return. Fewer than n namespaces may be returned. contiguous: If True then the returned NamespaceRanges will cover the entire space of possible namespaces (i.e. from MIN_NAMESPACE to MAX_NAMESPACE)...
@classmethod def split(cls, n, contiguous, can_query=itertools.chain(itertools.repeat(True, 50), itertools.repeat(False)).next, _app=None):
if (n < 1): raise ValueError('n must be >= 1') ns_range = NamespaceRange(_app=_app) if can_query(): ns_range = ns_range.normalized_start() if (ns_range is None): if contiguous: return [NamespaceRange(_app=_app)] else: ...
'Iterate over all the namespaces within this range.'
def __iter__(self):
query = self.make_datastore_query() for ns_key in query.Run(): (yield (ns_key.name() or ''))
'Init. Args: filename: filename in str. file_range: [start_index, end_index) tuple. This only makes sense for _FileFormats that support splitting within a file. It specify the range to read this file. None means reading the entire file. When defined, what it means differ for each format. For example, if a file is of zi...
def __init__(self, filename, file_range=None):
self.filename = filename self.range = file_range
'Init. Args: formats: A list of _FileFormats. inputs: A list of _FileRanges. init_files_streams: If to initialize files streams to default value.'
def __init__(self, formats, inputs, files_streams_json=None):
self._inputs = inputs self._formats = formats for (i, file_format) in enumerate(self._formats): stream_cls = (_RootFilesStream if (i == 0) else _FilesStream) if files_streams_json: file_format._input_files_stream = stream_cls.from_json(files_streams_json[i], self) else: ...
'Iterate over inputs.'
def next(self):
result = self._formats[(-1)].next() self._formats[(-1)]._input_files_stream.checkpoint() self._formats[(-1)].checkpoint() return result
'Init. Args: file_format_root: the FileFormatRoot this stream should talk to. index: the index of this stream within the FileFormatRoot. offset: the offset to start reading current file. next_func: a function that gives back the next file from the stream.'
def __init__(self, index, file_format_root, offset=0, next_func=None):
self._next_file = (next_func or file_format_root._formats[(index - 1)].next) self._preprocess = file_format_root._formats[index].preprocess self._previous_offset = offset self._index = index self._current = self._preprocess(self._next_file()) self._current.seek(offset)
'Advance _current to the next file-like object. _FileStream should call this after consumed the current file-like object.'
def advance(self):
self._previous_offset = 0 self._current.close() self._current = self._preprocess(self._next_file())
'Init. Args: index: the index of this stream within the FileFormatRoot. file_format_root: the FileFormatRoot this stream should talk to. offset: the offset to start reading current file. input_index: index of the next input file to read.'
def __init__(self, index, file_format_root, offset=0, input_index=0):
self.__inputs = file_format_root._inputs self.__input_index = input_index self.__previous_input_index = input_index self.__file_format_root = file_format_root super(_RootFilesStream, self).__init__(index, file_format_root, offset, self.next_file)
'Validates mapper specification. Output writer parameters are expected to be passed as "output_writer" subdictionary of mapper_spec.params. To be compatible with previous API output writer is advised to check mapper_spec.params and issue a warning if "output_writer" subdicationary is not present. _get_params helper met...
@classmethod def validate(cls, mapper_spec):
raise NotImplementedError(('validate() not implemented in %s' % cls))
'Initialize job-level writer state. Args: mapreduce_state: an instance of model.MapreduceState describing current job. State can be modified during initialization.'
@classmethod def init_job(cls, mapreduce_state):
raise NotImplementedError(('init_job() not implemented in %s' % cls))
'Finalize job-level writer state. Args: mapreduce_state: an instance of model.MapreduceState describing current job. State can be modified during finalization.'
@classmethod def finalize_job(cls, mapreduce_state):
raise NotImplementedError(('finalize_job() not implemented in %s' % cls))
'Creates an instance of the OutputWriter for the given json state. Args: state: The OutputWriter state as a dict-like object. Returns: An instance of the OutputWriter configured using the values of json.'
@classmethod def from_json(cls, state):
raise NotImplementedError(('from_json() not implemented in %s' % cls))
'Returns writer state to serialize in json. Returns: A json-izable version of the OutputWriter state.'
def to_json(self):
raise NotImplementedError(('to_json() not implemented in %s' % self.__class__))
'Create new writer for a shard. Args: mapreduce_state: an instance of model.MapreduceState describing current job. State can be modified. shard_state: shard state.'
@classmethod def create(cls, mapreduce_state, shard_state):
raise NotImplementedError(('create() not implemented in %s' % cls))
'Write data. Args: data: actual data yielded from handler. Type is writer-specific. ctx: an instance of context.Context.'
def write(self, data, ctx):
raise NotImplementedError(('write() not implemented in %s' % self.__class__))
'Finalize writer shard-level state. Args: ctx: an instance of context.Context. shard_state: shard state.'
def finalize(self, ctx, shard_state):
raise NotImplementedError(('finalize() not implemented in %s' % self.__class__))
'Obtain output filenames from mapreduce state. Args: mapreduce_state: an instance of model.MapreduceState Returns: list of filenames this writer writes to or None if writer doesn\'t write to a file.'
@classmethod def get_filenames(cls, mapreduce_state):
raise NotImplementedError(('get_filenames() not implemented in %s' % cls))
'Whether this output writer instance supports shard retry. Args: tstate: model.TransientShardState for current shard. Returns: boolean. Whether this output writer instance supports shard retry.'
def _can_be_retried(self, tstate):
return False
'Constructor. Args: flush_size_chars: buffer flush size in bytes as int. Internal buffer will be flushed once this size is reached. ctx: mapreduce context as context.Context. Can be null.'
def __init__(self, flush_size_chars=_FILES_API_FLUSH_SIZE, ctx=None):
self._flush_size = flush_size_chars self._append_buffer = {} self._size = 0 self._ctx = ctx
'Append data to the filename\'s buffer without checks and flushes.'
def __append(self, filename, data):
self._append_buffer[filename] = (self._append_buffer.get(filename, '') + data) self._size += len(data)
'Append data to a file. Args: filename: the name of the file as string. data: data as string.'
def append(self, filename, data):
if ((self._size + len(data)) > self._flush_size): self.flush() if (len(data) > _FILES_API_MAX_SIZE): raise errors.Error(("Can't write more than %s bytes in one request: risk of writes interleaving." % _FILES_API_MAX_SIZE)) else: self.__append(filen...
'Flush pool contents.'
def flush(self):
start_time = time.time() for (filename, data) in self._append_buffer.iteritems(): with files.open(filename, 'a') as f: if (len(data) > _FILES_API_MAX_SIZE): raise errors.Error(('Bad data of length: %s' % len(data))) if self._ctx: operat...
'Convert writer buffer to string.'
def to_string(self):
return self._buffer
'Write data. Args: data: data to append to the buffer as string.'
def write(self, data):
self._buffer += data
'Constructor. Args: filename: file name to write data to as string. flush_size_chars: buffer flush threshold as int. ctx: mapreduce context as context.Context. exclusive: a boolean flag indicating if the pool has an exclusive access to the file. If it is True, then it\'s possible to write bigger chunks of data.'
def __init__(self, filename, flush_size_chars=_FILES_API_FLUSH_SIZE, ctx=None, exclusive=False):
self._flush_size = flush_size_chars self._buffer = [] self._size = 0 self._filename = filename self._ctx = ctx self._exclusive = exclusive
'Append data to a file.'
def append(self, data):
data_length = len(data) if ((self._size + data_length) > self._flush_size): self.flush() if ((not self._exclusive) and (data_length > _FILES_API_MAX_SIZE)): raise errors.Error(('Too big input %s (%s).' % (data_length, _FILES_API_MAX_SIZE))) else: self._buffer.append(d...
'Flush pool contents.'
def flush(self):
buf = _StringWriter() with records.RecordsWriter(buf) as w: for record in self._buffer: w.write(record) str_buf = buf.to_string() if ((not self._exclusive) and (len(str_buf) > _FILES_API_MAX_SIZE)): raise errors.Error(("Buffer too big. Can't write more than ...
'State initializer. Args: filenames: writable or finalized filenames as returned by the files api. request_filenames: filenames as given to the files create api.'
def __init__(self, filenames, request_filenames):
self.filenames = filenames self.request_filenames = request_filenames
'Get output sharding parameter value from mapreduce state or mapper spec. At least one of the parameters should not be None. Args: mapreduce_state: mapreduce state as model.MapreduceState. mapper_spec: mapper specification as model.MapperSpec'
@classmethod def _get_output_sharding(cls, mapreduce_state=None, mapper_spec=None):
if mapper_spec: return _get_params(mapper_spec).get(FileOutputWriterBase.OUTPUT_SHARDING_PARAM, FileOutputWriterBase.OUTPUT_SHARDING_NONE).lower() if mapreduce_state: mapper_spec = mapreduce_state.mapreduce_spec.mapper return cls._get_output_sharding(mapper_spec=mapper_spec) raise er...
'Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate.'
@classmethod def validate(cls, mapper_spec):
if (mapper_spec.output_writer_class() != cls): raise errors.BadWriterParamsError('Output writer class mismatch') output_sharding = cls._get_output_sharding(mapper_spec=mapper_spec) if ((output_sharding != cls.OUTPUT_SHARDING_NONE) and (output_sharding != cls.OUTPUT_SHARDING_INPUT_SHARDS)): ...
'Initialize job-level writer state. Args: mapreduce_state: an instance of model.MapreduceState describing current job.'
@classmethod def init_job(cls, mapreduce_state):
output_sharding = cls._get_output_sharding(mapreduce_state=mapreduce_state) if (output_sharding == cls.OUTPUT_SHARDING_INPUT_SHARDS): mapreduce_state.writer_state = cls._State([], []).to_json() return mapper_spec = mapreduce_state.mapreduce_spec.mapper params = _get_params(mapper_spec) ...
'Creates a file and returns its created filename.'
@classmethod def _create_file(cls, filesystem, filename, mime_type, **kwargs):
if (filesystem == files.BLOBSTORE_FILESYSTEM): return files.blobstore.create(mime_type, filename) elif (filesystem == files.GS_FILESYSTEM): return files.gs.create(('/gs/%s' % filename), mime_type, **kwargs) else: raise errors.BadWriterParamsError(("Filesystem '%s' is not ...
'Returns the finalized filename for the created filename.'
@classmethod def _get_finalized_filename(cls, fs, create_filename, request_filename):
if (fs == 'blobstore'): return files.blobstore.get_file_name(files.blobstore.get_blob_key(create_filename)) elif (fs == 'gs'): return ('/gs/' + request_filename) else: raise errors.BadWriterParamsError(("Filesystem '%s' is not supported" % fs))
'Finalize job-level writer state. Collect from model.ShardState if this job has output per shard. Args: mapreduce_state: an instance of model.MapreduceState describing current job.'
@classmethod def finalize_job(cls, mapreduce_state):
state = cls._State.from_json(mapreduce_state.writer_state) output_sharding = cls._get_output_sharding(mapreduce_state=mapreduce_state) filesystem = cls._get_filesystem(mapreduce_state.mapreduce_spec.mapper) if (output_sharding != cls.OUTPUT_SHARDING_INPUT_SHARDS): files.finalize(state.filenames[...
'Creates an instance of the OutputWriter for the given json state. Args: state: The OutputWriter state as a json object (dict like). Returns: An instance of the OutputWriter configured using the values of json.'
@classmethod def from_json(cls, state):
return cls(state['filename'])
'Returns writer state to serialize in json. Returns: A json-izable version of the OutputWriter state.'
def to_json(self):
return {'filename': self._filename}
'Inherit doc. Only shard with output per shard can be retried.'
def _can_be_retried(self, tstate):
output_sharding = self._get_output_sharding(mapper_spec=tstate.mapreduce_spec.mapper) if (output_sharding == self.OUTPUT_SHARDING_INPUT_SHARDS): return True return False
'Create new writer for a shard. Args: mapreduce_state: an instance of model.MapreduceState describing current job. shard_state: an instance of mode.ShardState describing the shard outputing this file. Returns: an output writer instance for this shard.'
@classmethod def create(cls, mapreduce_state, shard_state):
output_sharding = cls._get_output_sharding(mapreduce_state=mapreduce_state) shard_number = shard_state.shard_number if (output_sharding == cls.OUTPUT_SHARDING_INPUT_SHARDS): mapper_spec = mapreduce_state.mapreduce_spec.mapper params = _get_params(mapper_spec) mime_type = params.get('...
'Finalize writer shard-level state. Args: ctx: an instance of context.Context. shard_state: shard state.'
def finalize(self, ctx, shard_state):
mapreduce_spec = ctx.mapreduce_spec output_sharding = self.__class__._get_output_sharding(mapper_spec=mapreduce_spec.mapper) if (output_sharding == self.OUTPUT_SHARDING_INPUT_SHARDS): filesystem = self._get_filesystem(mapreduce_spec.mapper) state = self._State.from_json(shard_state.writer_st...
'Obtain output filenames from mapreduce state. Args: mapreduce_state: an instance of model.MapreduceState Returns: list of filenames this writer writes to.'
@classmethod def get_filenames(cls, mapreduce_state):
state = cls._State.from_json(mapreduce_state.writer_state) return state.filenames
'Write data. Args: data: actual data yielded from handler. Type is writer-specific. ctx: an instance of context.Context.'
def write(self, data, ctx):
if (ctx.get_pool('file_pool') is None): ctx.register_pool('file_pool', _FilePool(ctx=ctx)) ctx.get_pool('file_pool').append(self._filename, str(data))
'Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate.'
@classmethod def validate(cls, mapper_spec):
if (cls.OUTPUT_SHARDING_PARAM in _get_params(mapper_spec)): raise errors.BadWriterParamsError(('output_sharding should not be specified for %s' % cls.__name__)) super(FileRecordsOutputWriter, cls).validate(mapper_spec)
'Write data. Args: data: actual data yielded from handler. Type is writer-specific. ctx: an instance of context.Context.'
def write(self, data, ctx):
if (ctx.get_pool('records_pool') is None): ctx.register_pool('records_pool', RecordsPool(self._filename, ctx=ctx, exclusive=True)) ctx.get_pool('records_pool').append(str(data))
'Create a RangeIterator. Args: p_range: a property_range.PropertyRange object that defines the conditions entities should safisfy. ns_range: a namesrange.NamespaceRange object that defines the namespaces to examine. query_spec: a model.QuerySpec object that defines how to retrieve entities from datastore. Returns: a Ra...
@classmethod def create_property_range_iterator(cls, p_range, ns_range, query_spec):
return _PropertyRangeModelIterator(p_range, ns_range, query_spec)
'Create a RangeIterator. Args: k_ranges: a key_ranges._KeyRanges object. query_spec: a model.query_spec object that defines how to retrieve entities from datastore. key_range_iter_cls: the class that iterates over a single key range. The value yielded by this class is yielded. Returns: a RangeIterator.'
@classmethod def create_key_ranges_iterator(cls, k_ranges, query_spec, key_range_iter_cls):
return _KeyRangesIterator(k_ranges, query_spec, key_range_iter_cls)
'Iter. Yields: Iterates over datastore entities and yields some kind of value for each entity.'
def __iter__(self):
raise NotImplementedError()
'Serializes all states into json form. Returns: all states in json-compatible map.'
def to_json(self):
raise NotImplementedError()
'Reverse of to_json.'
@classmethod def from_json(cls, json):
raise NotImplementedError()
'Init. Args: p_range: a property_range.PropertyRange object that defines the conditions entities should safisfy. ns_range: a namesrange.NamespaceRange object that defines the namespaces to examine. query_spec: a model.QuerySpec object that defines how to retrieve entities from datastore.'
def __init__(self, p_range, ns_range, query_spec):
self._property_range = p_range self._ns_range = ns_range self._query_spec = query_spec self._cursor = None self._query = None
'Iterate over entities. Yields: db model entities or ndb model entities if the model is defined with ndb.'
def __iter__(self):
for ns in self._ns_range: self._query = self._property_range.make_query(ns) if isinstance(self._query, db.Query): if self._cursor: self._query.with_cursor(self._cursor) for model_instance in self._query.run(batch_size=self._query_spec.batch_size, keys_only=sel...
'Inherit doc.'
def to_json(self):
cursor_object = False if (self._query is not None): if isinstance(self._query, db.Query): self._cursor = self._query.cursor() else: cursor_object = True self._cursor = self._query.cursor_after().to_websafe_string() else: self._cursor = None ret...
'Inherit doc.'
@classmethod def from_json(cls, json):
obj = cls(property_range.PropertyRange.from_json(json['property_range']), namespace_range.NamespaceRange.from_json_object(json['ns_range']), model.QuerySpec.from_json(json['query_spec'])) cursor = json['cursor'] if (cursor and json['cursor_object']): obj._cursor = datastore_query.Cursor.from_websafe...
'Init. Args: k_ranges: a key_ranges._KeyRanges object. query_spec: a model.query_spec object that defines how to retrieve entities from datastore. key_range_iter_cls: the class that iterates over a single key range. The value yielded by this class is yielded.'
def __init__(self, k_ranges, query_spec, key_range_iter_cls):
self._key_ranges = k_ranges self._query_spec = query_spec self._key_range_iter_cls = key_range_iter_cls self._current_iter = None self._current_key_range = None
'Inherit doc.'
def to_json(self):
current_iter = None if self._current_iter: current_iter = self._current_iter.to_json() return {'key_ranges': self._key_ranges.to_json(), 'query_spec': self._query_spec.to_json(), 'current_iter': current_iter, 'key_range_iter_cls': self._key_range_iter_cls.__name__, 'name': self.__class__.__name__}
'Inherit doc.'
@classmethod def from_json(cls, json):
key_range_iter_cls = _KEY_RANGE_ITERATORS[json['key_range_iter_cls']] obj = cls(key_ranges.KeyRangesFactory.from_json(json['key_ranges']), model.QuerySpec.from_json(json['query_spec']), key_range_iter_cls) current_iter = None if json['current_iter']: current_iter = key_range_iter_cls.from_json(j...
'Init. Args: k_range: a key_range.KeyRange object that defines the entity keys to operate on. KeyRange object already contains a namespace. query_spec: a model.query_spec object that defines how to retrieve entities from datastore.'
def __init__(self, k_range, query_spec):
self._key_range = k_range self._query_spec = query_spec self._cursor = None self._query = None
'Iter.'
def __iter__(self):
raise NotImplementedError()
'Get cursor on current query iterator for serialization.'
def _get_cursor(self):
raise NotImplementedError()
'Serializes all states into json form. Returns: all states in json-compatible map.'
def to_json(self):
cursor = self._get_cursor() cursor_object = False if (cursor and isinstance(cursor, datastore_query.Cursor)): cursor = cursor.to_websafe_string() cursor_object = True return {'key_range': self._key_range.to_json(), 'query_spec': self._query_spec.to_json(), 'cursor': cursor, 'cursor_objec...
'Reverse of to_json.'
@classmethod def from_json(cls, json):
obj = cls(key_range.KeyRange.from_json(json['key_range']), model.QuerySpec.from_json(json['query_spec'])) cursor = json['cursor'] if (cursor and json['cursor_object']): obj._cursor = datastore_query.Cursor.from_websafe_string(cursor) else: obj._cursor = cursor return obj
'Constructor.'
def __init__(self):
self.items = [] self.length = 0 self.size = 0
'Add new item to the list. Args: item: an item to add to the list. item_size: item size in bytes as int.'
def append(self, item, item_size):
self.items.append(item) self.length += 1 self.size += item_size
'Clear item list.'
def clear(self):
self.items = [] self.length = 0 self.size = 0
'Return items. For backwards compatability.'
@property def entities(self):
return self.items
'Constructor. Args: max_pool_size: maximum pools size in bytes before flushing it to db. max_entity_count: maximum number of entities before flushing it to db. mapreduce_spec: An optional instance of MapperSpec.'
def __init__(self, max_pool_size=MAX_POOL_SIZE, max_entity_count=MAX_ENTITY_COUNT, mapreduce_spec=None):
self.max_pool_size = max_pool_size self.max_entity_count = max_entity_count params = (mapreduce_spec.params if (mapreduce_spec is not None) else {}) self.force_writes = bool(params.get('force_ops_writes', False)) self.puts = ItemList() self.deletes = ItemList() self.ndb_puts = ItemList() ...
'Registers entity to put to datastore. Args: entity: an entity or model instance to put.'
def put(self, entity):
actual_entity = _normalize_entity(entity) if (actual_entity is None): return self.ndb_put(entity) entity_size = len(actual_entity._ToPb().Encode()) if ((self.puts.length >= self.max_entity_count) or ((self.puts.size + entity_size) > self.max_pool_size)): self.__flush_puts() self.puts...
'Like put(), but for NDB entities.'
def ndb_put(self, entity):
assert ((ndb is not None) and isinstance(entity, ndb.Model)) entity_size = len(entity._to_pb().Encode()) if ((self.ndb_puts.length >= self.max_entity_count) or ((self.ndb_puts.size + entity_size) > self.max_pool_size)): self.__flush_ndb_puts() self.ndb_puts.append(entity, entity_size)
'Registers entity to delete from datastore. Args: entity: an entity, model instance, or key to delete.'
def delete(self, entity):
key = _normalize_key(entity) if (key is None): return self.ndb_delete(entity) key_size = len(key._ToPb().Encode()) if ((self.deletes.length >= self.max_entity_count) or ((self.deletes.size + key_size) > self.max_pool_size)): self.__flush_deletes() self.deletes.append(key, key_size)
'Like delete(), but for NDB entities/keys.'
def ndb_delete(self, entity_or_key):
if isinstance(entity_or_key, ndb.Model): key = entity_or_key.key else: key = entity_or_key key_size = len(key.reference().Encode()) if ((self.ndb_deletes.length >= self.max_entity_count) or ((self.ndb_deletes.size + key_size) > self.max_pool_size)): self.__flush_ndb_deletes() ...
'Flush(apply) all changed to datastore.'
def flush(self):
self.__flush_puts() self.__flush_deletes() self.__flush_ndb_puts() self.__flush_ndb_deletes()
'Flush all puts to datastore.'
def __flush_puts(self):
if self.puts.length: datastore.Put(self.puts.items, config=self.__create_config()) self.puts.clear()
'Flush all deletes to datastore.'
def __flush_deletes(self):
if self.deletes.length: datastore.Delete(self.deletes.items, config=self.__create_config()) self.deletes.clear()
'Flush all NDB puts to datastore.'
def __flush_ndb_puts(self):
if self.ndb_puts.length: ndb.put_multi(self.ndb_puts.items, config=self.__create_config()) self.ndb_puts.clear()
'Flush all deletes to datastore.'
def __flush_ndb_deletes(self):
if self.ndb_deletes.length: ndb.delete_multi(self.ndb_deletes.items, config=self.__create_config()) self.ndb_deletes.clear()
'Creates datastore Config. Returns: A datastore_rpc.Configuration instance.'
def __create_config(self):
return datastore.CreateConfig(deadline=DATASTORE_DEADLINE, force_writes=self.force_writes)
'Constructor. Args: shard_state: current mapreduce shard state as model.ShardState.'
def __init__(self, shard_state):
self._shard_state = shard_state
'Increment counter value. Args: counter_name: name of the counter as string. delta: increment delta as int.'
def increment(self, counter_name, delta=1):
self._shard_state.counters_map.increment(counter_name, delta)
'Flush unsaved counter values.'
def flush(self):
pass
'Constructor. Args: mapreduce_spec: mapreduce specification as model.MapreduceSpec. shard_state: shard state as model.ShardState.'
def __init__(self, mapreduce_spec, shard_state, task_retry_count=0):
self.mapreduce_spec = mapreduce_spec self.shard_state = shard_state self.task_retry_count = task_retry_count if self.mapreduce_spec: self.mapreduce_id = self.mapreduce_spec.mapreduce_id else: self.mapreduce_id = None if self.shard_state: self.shard_id = self.shard_state.g...
'Flush all information recorded in context.'
def flush(self):
for pool in self._pools.values(): pool.flush()
'Register an arbitrary pool to be flushed together with this context. Args: key: pool key as string. pool: a pool instance. Pool should implement flush(self) method.'
def register_pool(self, key, pool):
self._pools[key] = pool
'Obtains an instance of registered pool. Args: key: pool key as string. Returns: an instance of the pool registered earlier, or None.'
def get_pool(self, key):
return self._pools.get(key, None)
'Set current context instance. Args: context: new context as Context or None.'
@classmethod def _set(cls, context):
cls._local._context_instance = context
'Initialize. Args: index: the index of the subfile to read from the current file. index_range: a tuple [start_index, end_index) that if defined, should bound index. When index is end_index, current file is consumed. kwargs: kwargs for a specific FileFormat. What arguments are accepted and their semantics depend on each...
def __init__(self, index, index_range=None, **kwargs):
for k in kwargs: if (k not in self.ARGUMENTS): raise ValueError(('Illegal argument %s' % k)) self._kwargs = kwargs self._index = index self._previous_index = index self._range = index_range self._input_files_stream = None self._cache = {}
'Get the current file to iterate upon. Returns: A Python file object. This file is already seeked to the position from last iteration. If read raises EOF, that means the file is exhausted.'
def get_current_file(self):
return self._input_files_stream.current
'Get index. If the format is an archive format, get_index() tells the format which subfile from current file should it process. This value is maintained across pickles and resets to 0 when a new file starts. Returns: index of the subfile to process from current file.'
def get_index(self):
return self._index
'Increment index. Increment index value after finished processing the current subfile from current file.'
def increment_index(self):
self._index += 1