desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Schedule slice scanning by adding it to the task queue. Args: worker_task: a util.HugeTask task for slice. This is NOT a taskqueue task. shard_state: an instance of ShardState. mapreduce_spec: an instance of model.MapreduceSpec. queue_name: Optional queue to run on; uses the current queue of execution or the default q...
@classmethod def _add_task(cls, worker_task, shard_state, mapreduce_spec, queue_name):
if (not _run_task_hook(mapreduce_spec.get_hooks(), 'enqueue_worker_task', worker_task, queue_name)): try: worker_task.add(queue_name, parent=shard_state) except (taskqueue.TombstonedTaskError, taskqueue.TaskAlreadyExistsError) as e: logging.warning('Task %r already e...
'Get the limit on the number of map calls allowed by this slice. Args: spec: a Mapreduce spec. Returns: The limit as a positive int if specified by user. -1 otherwise.'
def _processing_limit(self, spec):
processing_rate = float(spec.mapper.params.get('processing_rate', 0)) slice_processing_limit = (-1) if (processing_rate > 0): slice_processing_limit = int(math.ceil(((_SLICE_DURATION_SEC * processing_rate) / int(spec.mapper.shard_count)))) return slice_processing_limit
'Schedule slice scanning by adding it to the task queue. Args: shard_state: An instance of ShardState. tstate: An instance of TransientShardState. queue_name: Optional queue to run on; uses the current queue of execution or the default queue if unspecified. eta: Absolute time when the MR should execute. May not be spec...
@classmethod def _schedule_slice(cls, shard_state, tstate, queue_name=None, eta=None, countdown=None):
queue_name = (queue_name or os.environ.get('HTTP_X_APPENGINE_QUEUENAME', 'default')) task = cls._state_to_task(tstate, eta, countdown) cls._add_task(task, shard_state, tstate.mapreduce_spec, queue_name)
'Constructor.'
def __init__(self, *args):
super(ControllerCallbackHandler, self).__init__(*args) self._time = time.time
'Handle request.'
def handle(self):
spec = model.MapreduceSpec.from_json_str(self.request.get('mapreduce_spec')) (state, control) = db.get([model.MapreduceState.get_key_by_job_id(spec.mapreduce_id), model.MapreduceControl.get_key_by_job_id(spec.mapreduce_id)]) if (not state): logging.error("State not found for MR '%s'; ...
'Update mr state by examing shard states. Args: state: current mapreduce state as MapreduceState. shard_states: all shard states (active and inactive). list of ShardState. control: model.MapreduceControl entity.'
def _update_state_from_shard_states(self, state, shard_states, control):
active_shards = [s for s in shard_states if s.active] failed_shards = [s for s in shard_states if (s.result_status == model.ShardState.RESULT_FAILED)] aborted_shards = [s for s in shard_states if (s.result_status == model.ShardState.RESULT_ABORTED)] spec = state.mapreduce_spec state.active = bool(ac...
'Update stats in mapreduce state by aggregating stats from shard states. Args: mapreduce_state: current mapreduce state as MapreduceState. shard_states: all shard states (active and inactive). list of ShardState.'
def _aggregate_stats(self, mapreduce_state, shard_states):
processed_counts = [] mapreduce_state.counters_map.clear() for shard_state in shard_states: mapreduce_state.counters_map.add_map(shard_state.counters_map) processed_counts.append(shard_state.counters_map.get(context.COUNTER_MAPPER_CALLS)) mapreduce_state.set_processed_counts(processed_co...
'Get serial unique identifier of this task from request. Returns: serial identifier as int.'
def serial_id(self):
return int(self.request.get('serial_id'))
'Finalize job execution. Finalizes output writer, invokes done callback and save mapreduce state in a transaction, and schedule necessary clean ups. Args: mapreduce_spec: an instance of MapreduceSpec mapreduce_state: an instance of MapreduceState base_path: handler_base path.'
@classmethod def _finalize_job(cls, mapreduce_spec, mapreduce_state, base_path):
config = util.create_datastore_write_config(mapreduce_spec) if (mapreduce_spec.mapper.output_writer_class() and (mapreduce_state.result_status == model.MapreduceState.RESULT_SUCCESS)): mapreduce_spec.mapper.output_writer_class().finalize_job(mapreduce_state) queue_name = mapreduce_spec.params.get(mo...
'Compute single controller task name. Args: transient_shard_state: an instance of TransientShardState. Returns: task name which should be used to process specified shard/slice.'
@staticmethod def get_task_name(mapreduce_spec, serial_id):
return ('appengine-mrcontrol-%s-%s' % (mapreduce_spec.mapreduce_id, serial_id))
'Fill in controller task parameters. Returned parameters map is to be used as task payload, and it contains all the data, required by controller to perform its function. Args: mapreduce_spec: specification of the mapreduce. serial_id: id of the invocation as int. Returns: string->string map of parameters to be used as...
@staticmethod def controller_parameters(mapreduce_spec, serial_id):
return {'mapreduce_spec': mapreduce_spec.to_json_str(), 'serial_id': str(serial_id)}
'Schedule new update status callback task. Args: mapreduce_state: mapreduce state as model.MapreduceState base_path: mapreduce handlers url base path as string. mapreduce_spec: mapreduce specification as MapreduceSpec. serial_id: id of the invocation as int. queue_name: The queue to schedule this task on. Will use the ...
@classmethod def reschedule(cls, mapreduce_state, base_path, mapreduce_spec, serial_id, queue_name=None):
task_name = ControllerCallbackHandler.get_task_name(mapreduce_spec, serial_id) task_params = ControllerCallbackHandler.controller_parameters(mapreduce_spec, serial_id) if (not queue_name): queue_name = os.environ.get('HTTP_X_APPENGINE_QUEUENAME', 'default') controller_callback_task = util.HugeTa...
'Handles kick off request.'
def handle(self):
spec = model.MapreduceSpec.from_json_str(self._get_required_param('mapreduce_spec')) app_id = self.request.get('app', None) queue_name = os.environ.get('HTTP_X_APPENGINE_QUEUENAME', 'default') mapper_input_reader_class = spec.mapper.input_reader_class() state = model.MapreduceState.create_new(spec.m...
'Get a required request parameter. Args: param_name: name of request parameter to fetch. Returns: parameter value Raises: errors.NotEnoughArgumentsError: if parameter is not specified.'
def _get_required_param(self, param_name):
value = self.request.get(param_name) if (not value): raise errors.NotEnoughArgumentsError((param_name + ' not specified')) return value
'Prepares shard states and schedules their execution. Args: spec: mapreduce specification as MapreduceSpec. input_readers: list of InputReaders describing shard splits. queue_name: The queue to run this job on. base_path: The base url path of mapreduce callbacks. mr_state: The MapReduceState of current job.'
@classmethod def _schedule_shards(cls, spec, input_readers, queue_name, base_path, mr_state):
shard_states = [] writer_class = spec.mapper.output_writer_class() output_writers = ([None] * len(input_readers)) for (shard_number, input_reader) in enumerate(input_readers): shard_state = model.ShardState.create_new(spec.mapreduce_id, shard_number) shard_state.shard_description = str(i...
'Handles start request.'
def handle(self):
mapreduce_name = self._get_required_param('name') mapper_input_reader_spec = self._get_required_param('mapper_input_reader') mapper_handler_spec = self._get_required_param('mapper_handler') mapper_output_writer_spec = self.request.get('mapper_output_writer') mapper_params = self._get_params('mapper_...
'Retrieves additional user-supplied params for the job and validates them. Args: validator_parameter: name of the request parameter which supplies validator for this parameter set. name_prefix: common prefix for all parameter names in the request. Raises: Any exception raised by the \'params_validator\' request paramet...
def _get_params(self, validator_parameter, name_prefix):
params_validator = self.request.get(validator_parameter) user_params = {} for key in self.request.arguments(): if key.startswith(name_prefix): values = self.request.get_all(key) adjusted_key = key[len(name_prefix):] if (len(values) == 1): user_para...
'Get a required request parameter. Args: param_name: name of request parameter to fetch. Returns: parameter value Raises: errors.NotEnoughArgumentsError: if parameter is not specified.'
def _get_required_param(self, param_name):
value = self.request.get(param_name) if (not value): raise errors.NotEnoughArgumentsError((param_name + ' not specified')) return value
'Schedule finalize task. Args: mapreduce_spec: mapreduce specification as MapreduceSpec.'
@classmethod def schedule(cls, base_path, mapreduce_spec):
task_name = (mapreduce_spec.mapreduce_id + '-finalize') finalize_task = taskqueue.Task(name=task_name, url=(base_path + '/finalizejob_callback'), params={'mapreduce_id': mapreduce_spec.mapreduce_id}) queue_name = os.environ.get('HTTP_X_APPENGINE_QUEUENAME', 'default') if (not _run_task_hook(mapreduce_sp...
'Init. Args: filters: user supplied filters. Each filter should be a list or tuple of format (<property_name_as_str>, <query_operator_as_str>, <value_of_certain_type>). Value type should satisfy the property\'s type. model_class_path: full path to the model class in str.'
def __init__(self, filters, model_class_path):
self.filters = filters self.model_class_path = model_class_path self.model_class = util.for_name(self.model_class_path) (self.prop, self.start, self.end) = self._get_range_from_filters(self.filters, self.model_class)
'Get property range from filters user provided. This method also validates there is one and only one closed range on a single property. Args: filters: user supplied filters. Each filter should be a list or tuple of format (<property_name_as_str>, <query_operator_as_str>, <value_of_certain_type>). Value type should sati...
@classmethod def _get_range_from_filters(cls, filters, model_class):
if (not filters): return (None, None, None) range_property = None start_val = None end_val = None start_filter = None end_filter = None for f in filters: (prop, op, val) = f if (op in ['>', '>=', '<', '<=']): if (range_property and (range_property != prop)...
'Evenly split this range into contiguous, non overlapping subranges. Args: n: number of splits. Returns: a list of contiguous, non overlapping sub PropertyRanges. Maybe less than n when not enough subranges.'
def split(self, n):
new_range_filters = [] name = self.start[0] prop_cls = self.prop.__class__ if (prop_cls in _DISCRETE_PROPERTY_SPLIT_FUNCTIONS): splitpoints = _DISCRETE_PROPERTY_SPLIT_FUNCTIONS[prop_cls](self.start[2], self.end[2], n, (self.start[1] == '>='), (self.end[1] == '<=')) start_filter = (name, ...
'Make a query of entities within this range. Query options are not supported. They should be specified when the query is run. Args: ns: namespace of this query. Returns: a db.Query or ndb.Query, depends on the model class\'s type.'
def make_query(self, ns):
if issubclass(self.model_class, db.Model): query = db.Query(self.model_class, namespace=ns) for f in self.filters: query.filter(('%s %s' % (f[0], f[1])), f[2]) else: query = self.model_class.query(namespace=ns) for f in self.filters: query = query.filte...
'Returns the next input from this input reader as a key, value pair. Returns: The next input from this input reader.'
def next(self):
raise NotImplementedError(('next() not implemented in %s' % self.__class__))
'Creates an instance of the InputReader for the given input shard state. Args: input_shard_state: The InputReader state as a dict-like object. Returns: An instance of the InputReader configured using the values of json.'
@classmethod def from_json(cls, input_shard_state):
raise NotImplementedError(('from_json() not implemented in %s' % cls))
'Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader.'
def to_json(self):
raise NotImplementedError(('to_json() not implemented in %s' % self.__class__))
'Returns a list of input readers. This method creates a list of input readers, each for one shard. It attempts to split inputs among readers evenly. Args: mapper_spec: model.MapperSpec specifies the inputs and additional parameters to define the behavior of input readers. Returns: A list of InputReaders.'
@classmethod def split_input(cls, mapper_spec):
raise NotImplementedError(('split_input() not implemented in %s' % cls))
'Validates mapper spec and all mapper parameters. Input reader parameters are expected to be passed as "input_reader" subdictionary in mapper_spec.params. Pre 1.6.4 API mixes input reader parameters with all other parameters. Thus to be compatible, input reader check mapper_spec.params as well and issue a warning if "i...
@classmethod def validate(cls, mapper_spec):
if (mapper_spec.input_reader_class() != cls): raise BadReaderParamsError('Input reader class mismatch')
'Initialize input reader. Args: format_root: a FileFormatRoot instance.'
def __init__(self, format_root):
self._file_format_root = format_root
'Inherit docs.'
def __iter__(self):
return self
'Inherit docs.'
def next(self):
ctx = context.get() start_time = time.time() content = self._file_format_root.next().read() if ctx: operation.counters.Increment(COUNTER_IO_READ_MSEC, int(((time.time() - start_time) * 1000)))(ctx) operation.counters.Increment(COUNTER_IO_READ_BYTES, len(content))(ctx) return content
'Inherit docs.'
@classmethod def split_input(cls, mapper_spec):
params = _get_params(mapper_spec) filenames = [] for f in params[cls.FILES_PARAM]: parsedName = files.gs.parseGlob(f) if isinstance(parsedName, tuple): filenames.extend(files.gs.listdir(parsedName[0], {'prefix': parsedName[1]})) else: filenames.append(parsedNa...
'Inherit docs.'
@classmethod def validate(cls, mapper_spec):
if (mapper_spec.input_reader_class() != cls): raise BadReaderParamsError('Mapper input reader class mismatch') params = _get_params(mapper_spec) if (cls.FILES_PARAM not in params): raise BadReaderParamsError(('Must specify %s' % cls.FILES_PARAM)) if (cls.FORMAT_PARAM no...
'Inherit docs.'
@classmethod def from_json(cls, json):
return cls(file_format_root.FileFormatRoot.from_json(json['file_format_root']))
'Inherit docs.'
def to_json(self):
return {'file_format_root': self._file_format_root.to_json()}
'Create new DatastoreInputReader object. This is internal constructor. Use split_input to create readers instead. Args: iterator: an iterator that generates objects for this input reader.'
def __init__(self, iterator):
self._iter = iterator
'Yields whatever internal iterator yields.'
def __iter__(self):
for o in self._iter: (yield o)
'Returns the string representation of this InputReader.'
def __str__(self):
return repr(self._iter)
'Serializes input reader to json compatible format. Returns: all the data in json-compatible map.'
def to_json(self):
return self._iter.to_json()
'Create new DatastoreInputReader from json, encoded by to_json. Args: json: json representation of DatastoreInputReader. Returns: an instance of DatastoreInputReader with all data deserialized from json.'
@classmethod def from_json(cls, json):
return cls(db_iters.RangeIteratorFactory.from_json(json))
'Construct a model.QuerySpec from model.MapperSpec.'
@classmethod def _get_query_spec(cls, mapper_spec):
params = _get_params(mapper_spec) entity_kind = params[cls.ENTITY_KIND_PARAM] filters = params.get(cls.FILTERS_PARAM) app = params.get(cls._APP_PARAM) ns = params.get(cls.NAMESPACE_PARAM) return model.QuerySpec(entity_kind=cls._get_raw_entity_kind(entity_kind), keys_only=bool(params.get(cls.KEY_...
'Inherit doc.'
@classmethod def split_input(cls, mapper_spec):
shard_count = mapper_spec.shard_count query_spec = cls._get_query_spec(mapper_spec) namespaces = None if (query_spec.ns is not None): k_ranges = cls._to_key_ranges_by_shard(query_spec.app, [query_spec.ns], shard_count, query_spec) else: ns_keys = namespace_range.get_namespace_keys(qu...
'Get a list of key_ranges.KeyRanges objects, one for each shard. This method uses scatter index to split each namespace into pieces and assign those pieces to shards. Args: app: app_id in str. namespaces: a list of namespaces in str. shard_count: number of shards to split. query_spec: model.QuerySpec. Returns: a list o...
@classmethod def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec):
key_ranges_by_ns = [] for namespace in namespaces: ranges = cls._split_ns_by_scatter(shard_count, namespace, query_spec.entity_kind, app) random.shuffle(ranges) key_ranges_by_ns.append(ranges) ranges_by_shard = [[] for _ in range(shard_count)] for ranges in key_ranges_by_ns: ...
'Split a namespace by scatter index into key_range.KeyRange. Args: shard_count: number of shards. namespace: namespace name to split. str. raw_entity_kind: low level datastore API entity kind. app: app id in str. Returns: A list of key_range.KeyRange objects. If there are not enough entities to splits into requested sh...
@classmethod def _split_ns_by_scatter(cls, shard_count, namespace, raw_entity_kind, app):
if (shard_count == 1): return [key_range.KeyRange(namespace=namespace, _app=app)] ds_query = datastore.Query(kind=raw_entity_kind, namespace=namespace, _app=app, keys_only=True) ds_query.Order('__scatter__') oversampling_factor = 32 random_keys = ds_query.Get((shard_count * oversampling_fact...
'Returns the best split points given a random set of datastore.Keys.'
@classmethod def _choose_split_points(cls, sorted_keys, shard_count):
assert (len(sorted_keys) >= shard_count) index_stride = (len(sorted_keys) / float(shard_count)) return [sorted_keys[int(round((index_stride * i)))] for i in range(1, shard_count)]
'Inherit docs.'
@classmethod def validate(cls, mapper_spec):
params = _get_params(mapper_spec) if (cls.ENTITY_KIND_PARAM not in params): raise BadReaderParamsError("Missing input reader parameter 'entity_kind'") if (cls.BATCH_SIZE_PARAM in params): try: batch_size = int(params[cls.BATCH_SIZE_PARAM]) if (batch_size <...
'Returns the entity kind to use with low level datastore calls. Args: entity_kind_or_model_classpath: user specified entity kind or model classpath. Returns: the entity kind in str to use with low level datastore calls.'
@classmethod def _get_raw_entity_kind(cls, entity_kind_or_model_classpath):
return entity_kind_or_model_classpath
'Inherit docs.'
@classmethod def validate(cls, mapper_spec):
super(RawDatastoreInputReader, cls).validate(mapper_spec) params = _get_params(mapper_spec) entity_kind = params[cls.ENTITY_KIND_PARAM] if ('.' in entity_kind): logging.warning('. detected in entity kind %s specified for reader %s.Assuming entity kind contains...
'Inherit docs.'
@classmethod def validate(cls, mapper_spec):
super(DatastoreInputReader, cls).validate(mapper_spec) params = _get_params(mapper_spec) entity_kind = params[cls.ENTITY_KIND_PARAM] try: model_class = util.for_name(entity_kind) except ImportError as e: raise BadReaderParamsError(('Bad entity kind: %s' % e)) if (cls.FIL...
'Validate user supplied filters. Validate filters are on existing properties and filter values have valid semantics. Args: filters: user supplied filters. Each filter should be a list or tuple of format (<property_name_as_str>, <query_operator_as_str>, <value_of_certain_type>). Value type is up to the property\'s type....
@classmethod def _validate_filters(cls, filters, model_class):
if (not filters): return properties = model_class.properties() for f in filters: (prop, _, val) = f if (prop not in properties): raise errors.BadReaderParamsError('Property %s is not defined for entity type %s', prop, model_class.kind()) tr...
'Validate ndb.Model filters.'
@classmethod def _validate_filters_ndb(cls, filters, model_class):
if (not filters): return properties = model_class._properties for f in filters: (prop, _, val) = f if (prop not in properties): raise errors.BadReaderParamsError('Property %s is not defined for entity type %s', prop, model_class._get_kind()) ...
'Inherit docs.'
@classmethod def split_input(cls, mapper_spec):
shard_count = mapper_spec.shard_count query_spec = cls._get_query_spec(mapper_spec) if (not property_range.should_shard_by_property_range(query_spec.filters)): return super(DatastoreInputReader, cls).split_input(mapper_spec) p_range = property_range.PropertyRange(query_spec.filters, query_spec.m...
'Create new AbstractDatastoreInputReader object. This is internal constructor. Use split_query in a concrete class instead. Args: entity_kind: entity kind as string. key_ranges: a sequence of key_range.KeyRange instances to process. Only one of key_ranges or ns_range can be non-None. ns_range: a namespace_range.Namespa...
def __init__(self, entity_kind, key_ranges=None, ns_range=None, batch_size=_BATCH_SIZE, current_key_range=None, filters=None):
assert ((key_ranges is not None) or (ns_range is not None)), "must specify one of 'key_ranges' or 'ns_range'" assert ((key_ranges is None) or (ns_range is None)), "can't specify both 'key_ranges ' and 'ns_range'" self._entity_kind = entity_kind self._key_ranges = (key...
'Iterates over the given KeyRanges or NamespaceRange. This method iterates over the given KeyRanges or NamespaceRange and sets the self._current_key_range to the KeyRange currently being processed. It then delegates to the _iter_key_range method to yield that actual results. Yields: Forwards the objects yielded by the ...
def __iter__(self):
if (self._key_ranges is not None): for o in self._iter_key_ranges(): (yield o) elif (self._ns_range is not None): for o in self._iter_ns_range(): (yield o) else: assert False, 'self._key_ranges and self._ns_range are both None'
'Iterates over self._key_ranges, delegating to self._iter_key_range().'
def _iter_key_ranges(self):
while True: if (self._current_key_range is None): if self._key_ranges: self._current_key_range = self._key_ranges.pop() continue else: break for (key, o) in self._iter_key_range(copy.deepcopy(self._current_key_range)): ...
'Iterates over self._ns_range, delegating to self._iter_key_range().'
def _iter_ns_range(self):
while True: if (self._current_key_range is None): query = self._ns_range.make_datastore_query() namespace_result = query.Get(1) if (not namespace_result): break namespace = (namespace_result[0].name() or '') self._current_key_range ...
'Yields a db.Key and the value that should be yielded by self.__iter__(). Args: k_range: The key_range.KeyRange to iterate over. Yields: A 2-tuple containing the last db.Key processed and the value that should be yielded by __iter__. The returned db.Key will be used to determine the InputReader\'s current position in s...
def _iter_key_range(self, k_range):
raise NotImplementedError(('_iter_key_range() not implemented in %s' % self.__class__))
'Returns the string representation of this InputReader.'
def __str__(self):
if (self._ns_range is None): return repr(self._key_ranges) else: return repr(self._ns_range)
'Returns the best split points given a random set of db.Keys.'
@classmethod def _choose_split_points(cls, sorted_keys, shard_count):
assert (len(sorted_keys) >= shard_count) index_stride = (len(sorted_keys) / float(shard_count)) return [sorted_keys[int(round((index_stride * i)))] for i in range(1, shard_count)]
'Return KeyRange objects. Helper for _split_input_from_params. If there are not enough Entities to make all of the given shards, the returned list of KeyRanges will include Nones. The returned list will contain KeyRanges ordered lexographically with any Nones appearing at the end.'
@classmethod def _split_input_from_namespace(cls, app, namespace, entity_kind, shard_count):
raw_entity_kind = cls._get_raw_entity_kind(entity_kind) if (shard_count == 1): return [key_range.KeyRange(namespace=namespace, _app=app)] ds_query = datastore.Query(kind=raw_entity_kind, namespace=namespace, _app=app, keys_only=True) ds_query.Order('__scatter__') random_keys = ds_query.Get((...
'Return input reader objects. Helper for split_input.'
@classmethod def _split_input_from_params(cls, app, namespaces, entity_kind_name, params, shard_count):
key_ranges = [] for namespace in namespaces: key_ranges.extend(cls._split_input_from_namespace(app, namespace, entity_kind_name, shard_count)) shared_ranges = [[] for _ in range(shard_count)] for (i, k_range) in enumerate(key_ranges): shared_ranges[(i % shard_count)].append(k_range) ...
'Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.'
@classmethod def validate(cls, mapper_spec):
if (mapper_spec.input_reader_class() != cls): raise BadReaderParamsError('Input reader class mismatch') params = _get_params(mapper_spec) if (cls.ENTITY_KIND_PARAM not in params): raise BadReaderParamsError("Missing mapper parameter 'entity_kind'") if (cls.BATCH_SIZE_PA...
'Splits query into shards without fetching query results. Tries as best as it can to split the whole query result set into equal shards. Due to difficulty of making the perfect split, resulting shards\' sizes might differ significantly from each other. Args: mapper_spec: MapperSpec with params containing \'entity_kind\...
@classmethod def split_input(cls, mapper_spec):
params = _get_params(mapper_spec) entity_kind_name = params[cls.ENTITY_KIND_PARAM] batch_size = int(params.get(cls.BATCH_SIZE_PARAM, cls._BATCH_SIZE)) shard_count = mapper_spec.shard_count namespace = params.get(cls.NAMESPACE_PARAM) app = params.get(cls._APP_PARAM) filters = params.get(cls.F...
'Serializes all the data in this query range into json form. Returns: all the data in json-compatible map.'
def to_json(self):
if (self._key_ranges is None): key_ranges_json = None else: key_ranges_json = [] for k in self._key_ranges: if k: key_ranges_json.append(k.to_json()) else: key_ranges_json.append(None) if (self._ns_range is None): namesp...
'Create new DatastoreInputReader from the json, encoded by to_json. Args: json: json map representation of DatastoreInputReader. Returns: an instance of DatastoreInputReader with all data deserialized from json.'
@classmethod def from_json(cls, json):
if (json[cls.KEY_RANGE_PARAM] is None): key_ranges = None else: key_ranges = [] for k in json[cls.KEY_RANGE_PARAM]: if k: key_ranges.append(key_range.KeyRange.from_json(k)) else: key_ranges.append(None) if (json[cls.NAMESPACE_RA...
'Initializes this instance with the given blob key and character range. This BlobstoreInputReader will read from the first record starting after strictly after start_position until the first record ending at or after end_position (exclusive). As an exception, if start_position is 0, then this InputReader starts reading...
def __init__(self, blob_key, start_position, end_position):
self._blob_key = blob_key self._blob_reader = blobstore.BlobReader(blob_key, self._BLOB_BUFFER_SIZE, start_position) self._end_position = end_position self._has_iterated = False self._read_before_start = bool(start_position)
'Returns the next input from as an (offset, line) tuple.'
def next(self):
self._has_iterated = True if self._read_before_start: self._blob_reader.readline() self._read_before_start = False start_position = self._blob_reader.tell() if (start_position > self._end_position): raise StopIteration() line = self._blob_reader.readline() if (not line): ...
'Returns an json-compatible input shard spec for remaining inputs.'
def to_json(self):
new_pos = self._blob_reader.tell() if self._has_iterated: new_pos -= 1 return {self.BLOB_KEY_PARAM: self._blob_key, self.INITIAL_POSITION_PARAM: new_pos, self.END_POSITION_PARAM: self._end_position}
'Returns the string representation of this BlobstoreLineInputReader.'
def __str__(self):
return ('blobstore.BlobKey(%r):[%d, %d]' % (self._blob_key, self._blob_reader.tell(), self._end_position))
'Instantiates an instance of this InputReader for the given shard spec.'
@classmethod def from_json(cls, json):
return cls(json[cls.BLOB_KEY_PARAM], json[cls.INITIAL_POSITION_PARAM], json[cls.END_POSITION_PARAM])
'Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.'
@classmethod def validate(cls, mapper_spec):
if (mapper_spec.input_reader_class() != cls): raise BadReaderParamsError('Mapper input reader class mismatch') params = _get_params(mapper_spec) if (cls.BLOB_KEYS_PARAM not in params): raise BadReaderParamsError("Must specify 'blob_keys' for mapper input") blob...
'Returns a list of shard_count input_spec_shards for input_spec. Args: mapper_spec: The mapper specification to split from. Must contain \'blob_keys\' parameter with one or more blob keys. Returns: A list of BlobstoreInputReaders corresponding to the specified shards.'
@classmethod def split_input(cls, mapper_spec):
params = _get_params(mapper_spec) blob_keys = params[cls.BLOB_KEYS_PARAM] if isinstance(blob_keys, basestring): blob_keys = blob_keys.split(',') blob_sizes = {} for blob_key in blob_keys: blob_info = blobstore.BlobInfo.get(blobstore.BlobKey(blob_key)) blob_sizes[blob_key] = b...
'Initializes this instance with the given blob key and file range. This BlobstoreZipInputReader will read from the file with index start_index up to but not including the file with index end_index. Args: blob_key: the BlobKey that this input reader is processing. start_index: the index of the first file to read. end_in...
def __init__(self, blob_key, start_index, end_index, _reader=blobstore.BlobReader):
self._blob_key = blob_key self._start_index = start_index self._end_index = end_index self._reader = _reader self._zip = None self._entries = None
'Returns the next input from this input reader as (ZipInfo, opener) tuple. Returns: The next input from this input reader, in the form of a 2-tuple. The first element of the tuple is a zipfile.ZipInfo object. The second element of the tuple is a zero-argument function that, when called, returns the complete body of the...
def next(self):
if (not self._zip): self._zip = zipfile.ZipFile(self._reader(self._blob_key)) self._entries = self._zip.infolist()[self._start_index:self._end_index] self._entries.reverse() if (not self._entries): raise StopIteration() entry = self._entries.pop() self._start_index += 1 ...
'Read entry content. Args: entry: zip file entry as zipfile.ZipInfo. Returns: Entry content as string.'
def _read(self, entry):
start_time = time.time() content = self._zip.read(entry.filename) ctx = context.get() if ctx: operation.counters.Increment(COUNTER_IO_READ_BYTES, len(content))(ctx) operation.counters.Increment(COUNTER_IO_READ_MSEC, int(((time.time() - start_time) * 1000)))(ctx) return content
'Creates an instance of the InputReader for the given input shard state. Args: json: The InputReader state as a dict-like object. Returns: An instance of the InputReader configured using the values of json.'
@classmethod def from_json(cls, json):
return cls(json[cls.BLOB_KEY_PARAM], json[cls.START_INDEX_PARAM], json[cls.END_INDEX_PARAM])
'Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader.'
def to_json(self):
return {self.BLOB_KEY_PARAM: self._blob_key, self.START_INDEX_PARAM: self._start_index, self.END_INDEX_PARAM: self._end_index}
'Returns the string representation of this BlobstoreZipInputReader.'
def __str__(self):
return ('blobstore.BlobKey(%r):[%d, %d]' % (self._blob_key, self._start_index, self._end_index))
'Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.'
@classmethod def validate(cls, mapper_spec):
if (mapper_spec.input_reader_class() != cls): raise BadReaderParamsError('Mapper input reader class mismatch') params = _get_params(mapper_spec) if (cls.BLOB_KEY_PARAM not in params): raise BadReaderParamsError("Must specify 'blob_key' for mapper input") blob_k...
'Returns a list of input shard states for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Must contain \'blob_key\' parameter with one blob key. _reader: a callable that returns a file-like object for reading blobs. Used for dependency injection. Returns: A list of InputReaders spanning files wi...
@classmethod def split_input(cls, mapper_spec, _reader=blobstore.BlobReader):
params = _get_params(mapper_spec) blob_key = params[cls.BLOB_KEY_PARAM] zip_input = zipfile.ZipFile(_reader(blob_key)) files = zip_input.infolist() total_size = sum((x.file_size for x in files)) num_shards = min(mapper_spec.shard_count, cls._MAX_SHARD_COUNT) size_per_shard = (total_size // n...
'Initializes this instance with the given blob key and file range. This BlobstoreZipLineInputReader will read from the file with index start_file_index up to but not including the file with index end_file_index. It will return lines starting at offset within file[start_file_index] Args: blob_key: the BlobKey that this ...
def __init__(self, blob_key, start_file_index, end_file_index, offset, _reader=blobstore.BlobReader):
self._blob_key = blob_key self._start_file_index = start_file_index self._end_file_index = end_file_index self._initial_offset = offset self._reader = _reader self._zip = None self._entries = None self._filestream = None
'Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.'
@classmethod def validate(cls, mapper_spec):
if (mapper_spec.input_reader_class() != cls): raise BadReaderParamsError('Mapper input reader class mismatch') params = _get_params(mapper_spec) if (cls.BLOB_KEYS_PARAM not in params): raise BadReaderParamsError("Must specify 'blob_keys' for mapper input") blob...
'Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Must contain \'blob_keys\' parameter with one or more blob keys. _reader: a callable that returns a file-like object for reading blobs. Used for dependency injection. Returns: A list of InputReaders spanning the...
@classmethod def split_input(cls, mapper_spec, _reader=blobstore.BlobReader):
params = _get_params(mapper_spec) blob_keys = params[cls.BLOB_KEYS_PARAM] if isinstance(blob_keys, basestring): blob_keys = blob_keys.split(',') blob_files = {} total_size = 0 for blob_key in blob_keys: zip_input = zipfile.ZipFile(_reader(blob_key)) blob_files[blob_key] =...
'Returns the next line from this input reader as (lineinfo, line) tuple. Returns: The next input from this input reader, in the form of a 2-tuple. The first element of the tuple describes the source, it is itself a tuple (blobkey, filenumber, byteoffset). The second element of the tuple is the line found at that offset...
def next(self):
if (not self._filestream): if (not self._zip): self._zip = zipfile.ZipFile(self._reader(self._blob_key)) self._entries = self._zip.infolist()[self._start_file_index:self._end_file_index] self._entries.reverse() if (not self._entries): raise StopIterati...
'Return the offset of the next line to read.'
def _next_offset(self):
if self._filestream: offset = self._filestream.tell() if offset: offset -= 1 else: offset = self._initial_offset return offset
'Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader.'
def to_json(self):
return {self.BLOB_KEY_PARAM: self._blob_key, self.START_FILE_INDEX_PARAM: self._start_file_index, self.END_FILE_INDEX_PARAM: self._end_file_index, self.OFFSET_PARAM: self._next_offset()}
'Creates an instance of the InputReader for the given input shard state. Args: json: The InputReader state as a dict-like object. _reader: For dependency injection. Returns: An instance of the InputReader configured using the values of json.'
@classmethod def from_json(cls, json, _reader=blobstore.BlobReader):
return cls(json[cls.BLOB_KEY_PARAM], json[cls.START_FILE_INDEX_PARAM], json[cls.END_FILE_INDEX_PARAM], json[cls.OFFSET_PARAM], _reader)
'Returns the string representation of this reader. Returns: string blobkey:[start file num, end file num]:current offset.'
def __str__(self):
return ('blobstore.BlobKey(%r):[%d, %d]:%d' % (self._blob_key, self._start_file_index, self._end_file_index, self._next_offset()))
'Initialize input reader. Args: count: number of entries this shard should generate. string_length: the length of generated random strings.'
def __init__(self, count, string_length):
self._count = count self._string_length = string_length
'Apply all jobs in the given KeyRange.'
def _apply_key_range(self, k_range):
apply_range = copy.deepcopy(k_range) while True: unapplied_query = self._make_unapplied_query(apply_range) unapplied_jobs = unapplied_query.Get(limit=self._batch_size, config=datastore_rpc.Configuration(deadline=self.UNAPPLIED_QUERY_DEADLINE)) if (not unapplied_jobs): break ...
'Returns a datastore.Query that finds the unapplied keys in k_range.'
def _make_unapplied_query(self, k_range):
unapplied_query = k_range.make_ascending_datastore_query(kind=None, keys_only=True) unapplied_query[ConsistentKeyReader.UNAPPLIED_LOG_FILTER] = self.start_time_us return unapplied_query
'Apply all jobs implied by the given keys.'
def _apply_jobs(self, unapplied_jobs):
keys_to_apply = [] for key in unapplied_jobs: path = (key.to_path() + [ConsistentKeyReader.DUMMY_KIND, ConsistentKeyReader.DUMMY_ID]) keys_to_apply.append(db.Key.from_path(_app=key.app(), namespace=key.namespace(), *path)) db.get(keys_to_apply, config=datastore_rpc.Configuration(deadline=sel...
'Splits input into key ranges.'
@classmethod def split_input(cls, mapper_spec):
readers = super(ConsistentKeyReader, cls).split_input(mapper_spec) start_time_us = _get_params(mapper_spec).get(cls.START_TIME_US_PARAM, long((time.time() * 1000000.0))) for reader in readers: reader.start_time_us = start_time_us return readers
'Serializes all the data in this reader into json form. Returns: all the data in json-compatible map.'
def to_json(self):
json_dict = super(DatastoreKeyInputReader, self).to_json() json_dict[self.START_TIME_US_PARAM] = self.start_time_us return json_dict
'Create new ConsistentKeyReader from the json, encoded by to_json. Args: json: json map representation of ConsistentKeyReader. Returns: an instance of ConsistentKeyReader with all data deserialized from json.'
@classmethod def from_json(cls, json):
reader = super(ConsistentKeyReader, cls).from_json(json) reader.start_time_us = json[cls.START_TIME_US_PARAM] return reader
'Serializes all the data in this query range into json form. Returns: all the data in json-compatible map.'
def to_json(self):
return {self.NAMESPACE_RANGE_PARAM: self.ns_range.to_json_object(), self.BATCH_SIZE_PARAM: self._batch_size}
'Create new DatastoreInputReader from the json, encoded by to_json. Args: json: json map representation of DatastoreInputReader. Returns: an instance of DatastoreInputReader with all data deserialized from json.'
@classmethod def from_json(cls, json):
return cls(namespace_range.NamespaceRange.from_json_object(json[cls.NAMESPACE_RANGE_PARAM]), json[cls.BATCH_SIZE_PARAM])
'Validates mapper spec. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.'
@classmethod def validate(cls, mapper_spec):
if (mapper_spec.input_reader_class() != cls): raise BadReaderParamsError('Input reader class mismatch') params = _get_params(mapper_spec) if (cls.BATCH_SIZE_PARAM in params): try: batch_size = int(params[cls.BATCH_SIZE_PARAM]) if (batch_size < 1): ...
'Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Returns: A list of InputReaders.'
@classmethod def split_input(cls, mapper_spec):
batch_size = int(_get_params(mapper_spec).get(cls.BATCH_SIZE_PARAM, cls._BATCH_SIZE)) shard_count = mapper_spec.shard_count namespace_ranges = namespace_range.NamespaceRange.split(shard_count, contiguous=True) return [NamespaceInputReader(ns_range, batch_size) for ns_range in namespace_ranges]
'Constructor. Args: filenames: list of filenames. position: file position to start reading from as int.'
def __init__(self, filenames, position):
self._filenames = filenames if self._filenames: self._reader = records.RecordsReader(files.BufferedFile(self._filenames[0])) self._reader.seek(position) else: self._reader = None