code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
shard_id = self.request.headers[util._MR_SHARD_ID_TASK_HEADER] mr_id = self.request.headers[util._MR_ID_TASK_HEADER] shard_state, mr_state = db.get([ model.ShardState.get_key_by_shard_id(shard_id), model.MapreduceState.get_key_by_job_id(mr_id)]) if shard_state and shard_state.activ...
def _drop_gracefully(self)
Drop worker task gracefully. Set current shard_state to failed. Controller logic will take care of other shards and the entire MR.
3.875701
3.400436
1.139766
# Controller will tally shard_states and properly handle the situation. if not shard_state: logging.warning("State not found for shard %s; Possible spurious task " "execution. Dropping this task.", tstate.shard_id) return self._TASK_DIRECTIVE.DROP_TAS...
def _try_acquire_lease(self, shard_state, tstate)
Validate datastore and the task payload are consistent. If so, attempt to get a lease on this slice's execution. See model.ShardState doc on slice_start_time. Args: shard_state: model.ShardState from datastore. tstate: model.TransientShardState from taskqueue paylod. Returns: A _TAS...
5.12889
4.579345
1.120005
assert shard_state.slice_start_time is not None assert shard_state.slice_request_id is not None request_ids = [shard_state.slice_request_id] logs = None try: logs = list(logservice.fetch(request_ids=request_ids)) except (apiproxy_errors.FeatureNotEnabledError, apiproxy_errors....
def _has_old_request_ended(self, shard_state)
Whether previous slice retry has ended according to Logs API. Args: shard_state: shard state. Returns: True if the request of previous slice retry has ended. False if it has not or unknown.
5.036707
4.763941
1.057256
assert shard_state.slice_start_time is not None delta = now() - shard_state.slice_start_time duration = datetime.timedelta(seconds=secs) if delta < duration: return util.total_seconds(duration - delta) else: return 0
def _wait_time(self, shard_state, secs, now=datetime.datetime.now)
Time to wait until slice_start_time is secs ago from now. Args: shard_state: shard state. secs: duration in seconds. now: a func that gets now. Returns: 0 if no wait. A positive int in seconds otherwise. Always around up.
3.532794
3.039907
1.162139
@db.transactional def _tx(): fresh_state = model.ShardState.get_by_shard_id(shard_state.shard_id) if fresh_state and fresh_state.active: # Free lease. fresh_state.slice_start_time = None fresh_state.slice_request_id = None if slice_retry: fresh_state.sl...
def _try_free_lease(self, shard_state, slice_retry=False)
Try to free lease. A lightweight transaction to update shard_state and unset slice_start_time to allow the next retry to happen without blocking. We don't care if this fails or not because the lease will expire anyway. Under normal execution, _save_state_and_schedule_next is the exit point. It...
3.65593
3.442931
1.061865
if obj is None or not isinstance(obj, shard_life_cycle._ShardLifeCycle): return shard_context = shard_ctx or self.shard_context slice_context = slice_ctx or self.slice_context if begin_slice: if slice_id == 0: obj.begin_shard(shard_context) obj.begin_slice(slice_context) ...
def _maintain_LC(self, obj, slice_id, last_slice=False, begin_slice=True, shard_ctx=None, slice_ctx=None)
Makes sure shard life cycle interface are respected. Args: obj: the obj that may have implemented _ShardLifeCycle. slice_id: current slice_id last_slice: whether this is the last slice. begin_slice: whether this is the beginning or the end of a slice. shard_ctx: shard ctx for dependen...
2.517976
2.089126
1.205277
task_directive = self._set_state(shard_state, tstate, task_directive) self._save_state_and_schedule_next(shard_state, tstate, task_directive) context.Context._set(None)
def __return(self, shard_state, tstate, task_directive)
Handler should always call this as the last statement.
5.623734
5.078125
1.107443
processing_limit = self._processing_limit(tstate.mapreduce_spec) if processing_limit == 0: return finished_shard = True # Input reader may not be an iterator. It is only a container. iterator = iter(input_reader) while True: try: entity = iterator.next() except S...
def _process_inputs(self, input_reader, shard_state, tstate, ctx)
Read inputs, process them, and write out outputs. This is the core logic of MapReduce. It reads inputs from input reader, invokes user specified mapper function, and writes output with output writer. It also updates shard_state accordingly. e.g. if shard processing is done, set shard_state.active to Fa...
7.070332
6.882288
1.027323
if data is not input_readers.ALLOW_CHECKPOINT: self.slice_context.incr(context.COUNTER_MAPPER_CALLS) handler = transient_shard_state.handler if isinstance(handler, map_job.Mapper): handler(self.slice_context, data) else: if input_reader.expand_parameters: res...
def _process_datum(self, data, input_reader, ctx, transient_shard_state)
Process a single data piece. Call mapper handler on the data. Args: data: a datum to process. input_reader: input reader. ctx: mapreduce context transient_shard_state: transient shard state. Returns: True if scan should be continued, False if scan should be stopped.
5.348098
5.178436
1.032763
if task_directive in (self._TASK_DIRECTIVE.RETRY_TASK, self._TASK_DIRECTIVE.DROP_TASK): return task_directive if task_directive == self._TASK_DIRECTIVE.ABORT_SHARD: shard_state.set_for_abort() return task_directive if task_directive == self._TASK_DIRECTIVE....
def _set_state(self, shard_state, tstate, task_directive)
Set shard_state and tstate based on task_directive. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. task_directive: self._TASK_DIRECTIVE for current shard. Returns: A _TASK_DIRECTIVE enum. PROCEED_TASK if task should pro...
2.157817
1.708417
1.263051
spec = tstate.mapreduce_spec if task_directive == self._TASK_DIRECTIVE.DROP_TASK: return if task_directive in (self._TASK_DIRECTIVE.RETRY_SLICE, self._TASK_DIRECTIVE.RETRY_TASK): # Set HTTP code to 500. return self.retry_task() elif task_directive == sel...
def _save_state_and_schedule_next(self, shard_state, tstate, task_directive)
Save state and schedule task. Save shard state to datastore. Schedule next slice if needed. Set HTTP response code. No modification to any shard_state or tstate. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. task_direc...
4.054155
3.882209
1.044291
mapper_spec = tstate.mapreduce_spec.mapper if not (tstate.output_writer and tstate.output_writer._supports_slice_recovery(mapper_spec)): return self._TASK_DIRECTIVE.PROCEED_TASK tstate.output_writer = tstate.output_writer._recover( tstate.mapreduce_spec, shard_state.shard_num...
def _attempt_slice_recovery(self, shard_state, tstate)
Recover a slice. This is run when a slice had been previously attempted and output may have been written. If an output writer requires slice recovery, we run those logic to remove output duplicates. Otherwise we just retry the slice. If recovery is needed, then the entire slice will be dedicated ...
5.210247
3.54806
1.468478
shard_attempts = shard_state.retries + 1 if shard_attempts >= parameters.config.SHARD_MAX_ATTEMPTS: logging.warning( "Shard attempt %s exceeded %s max attempts.", shard_attempts, parameters.config.SHARD_MAX_ATTEMPTS) return self._TASK_DIRECTIVE.FAIL_TASK if tstate.outpu...
def _attempt_shard_retry(self, shard_state, tstate)
Whether to retry shard. This method may modify shard_state and tstate to prepare for retry or fail. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. Returns: A _TASK_DIRECTIVE enum. RETRY_SHARD if shard should be retried. FA...
2.919015
2.641019
1.105261
if (shard_state.slice_retries + 1 < parameters.config.TASK_MAX_DATA_PROCESSING_ATTEMPTS): logging.warning( "Slice %s %s failed for the %s of up to %s attempts " "(%s of %s taskqueue execution attempts). " "Will retry now.", tstate.shard_id, tstate...
def _attempt_slice_retry(self, shard_state, tstate)
Attempt to retry this slice. This method may modify shard_state and tstate to prepare for retry or fail. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. Returns: A _TASK_DIRECTIVE enum. RETRY_SLICE if slice should be retried. ...
4.504534
3.929968
1.146201
countdown = 0 if self._processing_limit(spec) != -1: countdown = max( int(parameters.config._SLICE_DURATION_SEC - (self._time() - self._start_time)), 0) return countdown
def _get_countdown_for_next_slice(self, spec)
Get countdown for next slice's task. When user sets processing rate, we set countdown to delay task execution. Args: spec: model.MapreduceSpec Returns: countdown in int.
7.43118
7.608047
0.976753
base_path = tstate.base_path task_name = MapperWorkerCallbackHandler.get_task_name( tstate.shard_id, tstate.slice_id, tstate.retries) headers = util._get_task_headers(tstate.mapreduce_spec.mapreduce_id) headers[util._MR_SHARD_ID_TASK_HEADER] = tstate.shard_id worker_t...
def _state_to_task(cls, tstate, shard_state, eta=None, countdown=None)
Generate task for slice according to current states. Args: tstate: An instance of TransientShardState. shard_state: An instance of ShardState. eta: Absolute time when the MR should execute. May not be specified if 'countdown' is also supplied. This may be timezone-aware or timezon...
4.576115
4.152748
1.101949
if not _run_task_hook(mapreduce_spec.get_hooks(), "enqueue_worker_task", worker_task, queue_name): try: # Not adding transactionally because worker_task has name. # Named task is not allowed for transactional ad...
def _add_task(cls, worker_task, mapreduce_spec, queue_name)
Schedule slice scanning by adding it to the task queue. Args: worker_task: a model.HugeTask task for slice. This is NOT a taskqueue task. mapreduce_spec: an instance of model.MapreduceSpec. queue_name: Optional queue to run on; uses the current queue of execution or the default qu...
5.036812
5.670114
0.888309
processing_rate = float(spec.mapper.params.get("processing_rate", 0)) slice_processing_limit = -1 if processing_rate > 0: slice_processing_limit = int(math.ceil( parameters.config._SLICE_DURATION_SEC*processing_rate/ int(spec.mapper.shard_count))) return slice_processing_l...
def _processing_limit(self, spec)
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.
5.894589
4.658962
1.265215
queue_name = queue_name or os.environ.get("HTTP_X_APPENGINE_QUEUENAME", "default") task = cls._state_to_task(tstate, shard_state, eta, countdown) cls._add_task(task, tstate.mapreduce_spec, queue_name)
def _schedule_slice(cls, shard_state, tstate, queue_name=None, eta=None, countdown=None)
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 th...
3.904112
4.911994
0.794812
mr_id = self.request.headers[util._MR_ID_TASK_HEADER] state = model.MapreduceState.get_by_job_id(mr_id) if not state or not state.active: return state.active = False state.result_status = model.MapreduceState.RESULT_FAILED config = util.create_datastore_write_config(state.mapreduce_s...
def _drop_gracefully(self)
Gracefully drop controller task. This method is called when decoding controller task payload failed. Upon this we mark ShardState and MapreduceState as failed so all tasks can stop. Writing to datastore is forced (ignore read-only mode) because we want the tasks to stop badly, and if force_writes ...
4.221106
3.611125
1.168917
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.warning("State not ...
def handle(self)
Handle request.
4.649042
4.486186
1.036302
# Initialize vars. state.active_shards, state.aborted_shards, state.failed_shards = 0, 0, 0 total_shards = 0 processed_counts = [] processed_status = [] state.counters_map.clear() # Tally across shard states once. for s in shard_states: total_shards += 1 status = 'unkno...
def _update_state_from_shard_states(self, state, shard_states, control)
Update mr state by examing shard states. Args: state: current mapreduce state as MapreduceState. shard_states: an iterator over shard states. control: model.MapreduceControl entity.
3.781816
3.54868
1.065697
# Only finalize the output writers if the job is successful. 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)
def _finalize_outputs(cls, mapreduce_spec, mapreduce_state)
Finalize outputs. Args: mapreduce_spec: an instance of MapreduceSpec. mapreduce_state: an instance of MapreduceState.
3.785046
4.377091
0.86474
config = util.create_datastore_write_config(mapreduce_spec) queue_name = util.get_queue_name(mapreduce_spec.params.get( model.MapreduceSpec.PARAM_DONE_CALLBACK_QUEUE)) done_callback = mapreduce_spec.params.get( model.MapreduceSpec.PARAM_DONE_CALLBACK) done_task = None if done_ca...
def _finalize_job(cls, mapreduce_spec, mapreduce_state)
Finalize job execution. Invokes done callback and save mapreduce state in a transaction, and schedule necessary clean ups. This method is idempotent. Args: mapreduce_spec: an instance of MapreduceSpec mapreduce_state: an instance of MapreduceState
3.341387
3.378464
0.989026
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_callbac...
def reschedule(cls, mapreduce_state, mapreduce_spec, serial_id, queue_name=None)
Schedule new update status callback task. Args: mapreduce_state: mapreduce state as model.MapreduceState 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 current queue of ex...
3.426455
3.477554
0.985306
# Get and verify mr state. mr_id = self.request.get("mapreduce_id") # Log the mr_id since this is started in an unnamed task logging.info("Processing kickoff for job %s", mr_id) state = model.MapreduceState.get_by_job_id(mr_id) if not self._check_mr_state(state, mr_id): return # ...
def handle(self)
Handles kick off request.
5.348391
5.097697
1.049178
mr_id = self.request.get("mapreduce_id") logging.error("Failed to kick off job %s", mr_id) state = model.MapreduceState.get_by_job_id(mr_id) if not self._check_mr_state(state, mr_id): return # Issue abort command just in case there are running tasks. config = util.create_datastore_w...
def _drop_gracefully(self)
See parent.
5.636039
5.50456
1.023885
serialized_input_readers_key = (self._SERIALIZED_INPUT_READERS_KEY % state.key().id_or_name()) serialized_input_readers = model._HugeTaskPayload.get_by_key_name( serialized_input_readers_key, parent=state) # Initialize input readers. input_reader_class =...
def _get_input_readers(self, state)
Get input readers. Args: state: a MapreduceState model. Returns: A tuple: (a list of input readers, a model._HugeTaskPayload entity). The payload entity contains the json serialized input readers. (None, None) when input reader inplitting returned no data to process.
3.357895
3.119151
1.076541
mr_id = state.key().id_or_name() fresh_state = model.MapreduceState.get_by_job_id(mr_id) if not self._check_mr_state(fresh_state, mr_id): return False if fresh_state.active_shards != 0: logging.warning( "Mapreduce %s already has active shards. Looks like spurious task " ...
def _save_states(self, state, serialized_readers_entity)
Run transaction to save state. Args: state: a model.MapreduceState entity. serialized_readers_entity: a model._HugeTaskPayload entity containing json serialized input readers. Returns: False if a fatal error is encountered and this task should be dropped immediately. True if tran...
4.712878
4.084819
1.153754
# Create shard states. shard_states = [] for shard_number, input_reader in enumerate(readers): shard_state = model.ShardState.create_new(spec.mapreduce_id, shard_number) shard_state.shard_description = str(input_reader) shard_states.append(shard_state) # Retrieves already existin...
def _schedule_shards(cls, spec, readers, queue_name, base_path, mr_state)
Prepares shard states and schedules their execution. Even though this method does not schedule shard task and save shard state transactionally, it's safe for taskqueue to retry this logic because the initial shard_state for each shard is the same from any retry. This is an important yet reasonable assu...
3.764115
3.469064
1.085052
if state is None: logging.warning( "Mapreduce State for job %s is missing. Dropping Task.", mr_id) return False if not state.active: logging.warning( "Mapreduce %s is not active. Looks like spurious task " "execution. Dropping Task.", mr_id) r...
def _check_mr_state(cls, state, mr_id)
Check MapreduceState. Args: state: an MapreduceState instance. mr_id: mapreduce id. Returns: True if state is valid. False if not and this task should be dropped.
4.978769
4.128577
1.205929
# Mapper spec as form arguments. 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") ...
def handle(self)
Handles start request.
3.386479
3.272982
1.034677
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_params[adjusted_key]...
def _get_params(self, validator_parameter, name_prefix)
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 '...
2.523559
2.522925
1.000251
value = self.request.get(param_name) if not value: raise errors.NotEnoughArgumentsError(param_name + " not specified") return value
def _get_required_param(self, param_name)
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.
4.089744
3.239428
1.26249
# pylint: disable=g-doc-args # pylint: disable=g-doc-return-or-yield # Validate input reader. mapper_input_reader_class = mapper_spec.input_reader_class() mapper_input_reader_class.validate(mapper_spec) # Validate output writer. mapper_output_writer_class = mapper_spec.output_writer_cl...
def _start_map(cls, name, mapper_spec, mapreduce_params, queue_name, eta=None, countdown=None, hooks_class_name=None, _app=None, in_xg_transaction=False)
See control.start_map. Requirements for this method: 1. The request that invokes this method can either be regular or from taskqueue. So taskqueue specific headers can not be used. 2. Each invocation transactionally starts an isolated mapreduce job with a unique id. MapreduceState should be i...
3.127779
3.177702
0.98429
state = model.MapreduceState.create_new(mapreduce_spec.mapreduce_id) state.mapreduce_spec = mapreduce_spec state.active = True state.active_shards = 0 if _app: state.app_id = _app config = util.create_datastore_write_config(mapreduce_spec) state.put(config=config) return state
def _create_and_save_state(cls, mapreduce_spec, _app)
Save mapreduce state to datastore. Save state to datastore so that UI can see it immediately. Args: mapreduce_spec: model.MapreduceSpec, _app: app id if specified. None otherwise. Returns: The saved Mapreduce state.
2.812469
3.142813
0.894889
params = {"mapreduce_id": mapreduce_spec.mapreduce_id} # Task is not named so that it can be added within a transaction. kickoff_task = taskqueue.Task( url=base_path + "/kickoffjob_callback/" + mapreduce_spec.mapreduce_id, headers=util._get_task_headers(mapreduce_spec.mapreduce_id), ...
def _add_kickoff_task(cls, base_path, mapreduce_spec, eta, countdown, queue_name)
Enqueues a new kickoff task.
3.32916
3.351873
0.993224
task_name = mapreduce_spec.mapreduce_id + "-finalize" finalize_task = taskqueue.Task( name=task_name, url=(mapreduce_spec.params["base_path"] + "/finalizejob_callback/" + mapreduce_spec.mapreduce_id), params={"mapreduce_id": mapreduce_spec.mapreduce_id}, headers...
def schedule(cls, mapreduce_spec)
Schedule finalize task. Args: mapreduce_spec: mapreduce specification as MapreduceSpec.
3.221651
3.287891
0.979853
if "input_reader" not in mapper_spec.params: message = ("Input reader's parameters should be specified in " "input_reader subdictionary.") if not allow_old or allowed_keys: raise errors.BadReaderParamsError(message) params = mapper_spec.params params = dict((str(n), v) for n, v...
def _get_params(mapper_spec, allowed_keys=None, allow_old=True)
Obtain input reader parameters. Utility function for input readers implementation. Fetches parameters from mapreduce specification giving appropriate usage warnings. Args: mapper_spec: The MapperSpec for the job allowed_keys: set of all allowed keys in parameters as strings. If it is not None, the...
2.502674
2.2342
1.120166
if shard_count == 1: # With one shard we don't need to calculate any split points at all. return [key_range.KeyRange(namespace=namespace, _app=app)] ds_query = datastore.Query(kind=raw_entity_kind, namespace=namespace, _app=app, ...
def _split_ns_by_scatter(cls, shard_count, namespace, raw_entity_kind, filters, app)
Split a namespace by scatter index into key_range.KeyRange. TODO(user): Power this with key_range.KeyRange.compute_split_points. 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. ...
2.789306
2.691544
1.036322
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)]
def _choose_split_points(cls, sorted_keys, shard_count)
Returns the best split points given a random set of datastore.Keys.
2.933829
2.668986
1.09923
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 < 1: raise BadR...
def validate(cls, mapper_spec)
Inherit docs.
2.069731
2.062214
1.003645
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 the dot.",...
def validate(cls, mapper_spec)
Inherit docs.
4.11891
4.083391
1.008698
super(DatastoreInputReader, cls).validate(mapper_spec) params = _get_params(mapper_spec) entity_kind = params[cls.ENTITY_KIND_PARAM] # Fail fast if Model cannot be located. try: model_class = util.for_name(entity_kind) except ImportError, e: raise BadReaderParamsError("Bad entit...
def validate(cls, mapper_spec)
Inherit docs.
3.584007
3.546192
1.010664
if not filters: return properties = model_class._properties for idx, f in enumerate(filters): prop, ineq, val = f if prop not in properties: raise errors.BadReaderParamsError( "Property %s is not defined for entity type %s", prop, model_class._get_ki...
def _validate_filters_ndb(cls, filters, model_class)
Validate ndb.Model filters.
4.646972
4.544138
1.02263
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) # Artificially increase the number of shards to get a more even spli...
def split_input(cls, mapper_spec)
Inherit docs.
3.890833
3.894628
0.999025
while True: if self._current_key_range is None: if self._key_ranges: self._current_key_range = self._key_ranges.pop() # The most recently popped key_range may be None, so continue here # to find the next keyrange that's valid. continue else: ...
def _iter_key_ranges(self)
Iterates over self._key_ranges, delegating to self._iter_key_range().
5.026529
4.492535
1.118863
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 = key_range.KeyRange( ...
def _iter_ns_range(self)
Iterates over self._ns_range, delegating to self._iter_key_range().
4.680722
4.401479
1.063443
raw_entity_kind = cls._get_raw_entity_kind(entity_kind) if shard_count == 1: # With one shard we don't need to calculate any splitpoints at all. return [key_range.KeyRange(namespace=namespace, _app=app)] ds_query = datastore.Query(kind=raw_entity_kind, names...
def _split_input_from_namespace(cls, app, namespace, entity_kind, shard_count)
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. Args: app: the app. namespace:...
2.386018
2.322933
1.027158
# pylint: disable=redefined-outer-name key_ranges = [] # KeyRanges for all namespaces for namespace in namespaces: key_ranges.extend( cls._split_input_from_namespace(app, namespace, entity_kind_name, ...
def _split_input_from_params(cls, app, namespaces, entity_kind_name, params, shard_count)
Return input reader objects. Helper for split_input.
3.424651
3.35904
1.019533
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_PARAM in params: t...
def validate(cls, mapper_spec)
Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.
2.103568
2.02946
1.036516
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(...
def split_input(cls, mapper_spec)
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 con...
3.518174
3.437121
1.023582
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: namespace_range_json = None ...
def to_json(self)
Serializes all the data in this query range into json form. Returns: all the data in json-compatible map.
1.939985
1.908547
1.016472
if json[cls.KEY_RANGE_PARAM] is None: # pylint: disable=redefined-outer-name 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...
def from_json(cls, json)
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.
2.097698
2.052743
1.0219
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: ...
def next(self)
Returns the next input from as an (offset, line) tuple.
3.615221
3.257577
1.109788
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}
def to_json(self)
Returns an json-compatible input shard spec for remaining inputs.
6.55948
5.451574
1.203227
return cls(json[cls.BLOB_KEY_PARAM], json[cls.INITIAL_POSITION_PARAM], json[cls.END_POSITION_PARAM])
def from_json(cls, json)
Instantiates an instance of this InputReader for the given shard spec.
6.337469
5.393517
1.175016
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_keys = params[cls.BLOB_KEYS_P...
def validate(cls, mapper_spec)
Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.
2.829176
2.653938
1.066029
params = _get_params(mapper_spec) blob_keys = params[cls.BLOB_KEYS_PARAM] if isinstance(blob_keys, basestring): # This is a mechanism to allow multiple blob keys (which do not contain # commas) in a single string. It may go away. blob_keys = blob_keys.split(",") blob_sizes = {} ...
def split_input(cls, mapper_spec)
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.
2.214325
2.106567
1.051153
if not self._zip: self._zip = zipfile.ZipFile(self._reader(self._blob_key)) # Get a list of entries, reversed so we can pop entries off in order self._entries = self._zip.infolist()[self._start_index:self._end_index] self._entries.reverse() if not self._entries: raise StopIter...
def next(self)
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, retu...
4.040734
3.553072
1.137251
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 co...
def _read(self, entry)
Read entry content. Args: entry: zip file entry as zipfile.ZipInfo. Returns: Entry content as string.
4.913154
4.29622
1.143599
return cls(json[cls.BLOB_KEY_PARAM], json[cls.START_INDEX_PARAM], json[cls.END_INDEX_PARAM])
def from_json(cls, json)
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.
5.301953
5.983547
0.886089
return {self.BLOB_KEY_PARAM: self._blob_key, self.START_INDEX_PARAM: self._start_index, self.END_INDEX_PARAM: self._end_index}
def to_json(self)
Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader.
3.936315
3.962543
0.993381
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_key = params[cls.BLOB_KEY_PARAM...
def validate(cls, mapper_spec)
Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.
3.048602
2.734187
1.114994
params = _get_params(mapper_spec) blob_key = params[cls.BLOB_KEY_PARAM] zip_input = zipfile.ZipFile(_reader(blob_key)) zfiles = zip_input.infolist() total_size = sum(x.file_size for x in zfiles) num_shards = min(mapper_spec.shard_count, cls._MAX_SHARD_COUNT) size_per_shard = total_size ...
def split_input(cls, mapper_spec, _reader=blobstore.BlobReader)
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: ...
2.130667
2.114821
1.007493
params = _get_params(mapper_spec) blob_keys = params[cls.BLOB_KEYS_PARAM] if isinstance(blob_keys, basestring): # This is a mechanism to allow multiple blob keys (which do not contain # commas) in a single string. It may go away. blob_keys = blob_keys.split(",") blob_files = {} ...
def split_input(cls, mapper_spec, _reader=blobstore.BlobReader)
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. Retur...
2.873805
2.843542
1.010643
if not self._filestream: if not self._zip: self._zip = zipfile.ZipFile(self._reader(self._blob_key)) # Get a list of entries, reversed so we can pop entries off in order self._entries = self._zip.infolist()[self._start_file_index: self....
def next(self)
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...
2.934108
2.834733
1.035056
if self._filestream: offset = self._filestream.tell() if offset: offset -= 1 else: offset = self._initial_offset return offset
def _next_offset(self)
Return the offset of the next line to read.
5.166189
4.294587
1.202954
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()}
def to_json(self)
Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader.
4.158895
3.66309
1.135352
return cls(json[cls.BLOB_KEY_PARAM], json[cls.START_FILE_INDEX_PARAM], json[cls.END_FILE_INDEX_PARAM], json[cls.OFFSET_PARAM], _reader)
def from_json(cls, json, _reader=blobstore.BlobReader)
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.
3.717105
4.163477
0.892789
return {self.NAMESPACE_RANGE_PARAM: self.ns_range.to_json_object(), self.BATCH_SIZE_PARAM: self._batch_size}
def to_json(self)
Serializes all the data in this query range into json form. Returns: all the data in json-compatible map.
11.883227
11.536929
1.030016
return cls( namespace_range.NamespaceRange.from_json_object( json[cls.NAMESPACE_RANGE_PARAM]), json[cls.BATCH_SIZE_PARAM])
def from_json(cls, json)
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.
8.494304
8.651111
0.981874
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: raise BadReaderParamsEr...
def validate(cls, mapper_spec)
Validates mapper spec. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.
2.57251
2.371127
1.084931
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 [NamespaceInp...
def split_input(cls, mapper_spec)
Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Returns: A list of InputReaders.
4.957789
5.8197
0.851898
# Strip out unrecognized parameters, as introduced by b/5960884. params = dict((str(k), v) for k, v in json.iteritems() if k in cls._PARAMS) # This is not symmetric with to_json() wrt. PROTOTYPE_REQUEST_PARAM because # the constructor parameters need to be JSON-encodable, so the ...
def from_json(cls, json)
Creates an instance of the InputReader for the given input shard's state. Args: json: The InputReader state as a dict-like object. Returns: An instance of the InputReader configured using the given JSON parameters.
7.515567
7.713594
0.974327
params = dict(self.__params) # Shallow copy. if self._PROTOTYPE_REQUEST_PARAM in params: prototype_request = params[self._PROTOTYPE_REQUEST_PARAM] params[self._PROTOTYPE_REQUEST_PARAM] = prototype_request.Encode() if self._OFFSET_PARAM in params: params[self._OFFSET_PARAM] = base64....
def to_json(self)
Returns an input shard state for the remaining inputs. Returns: A JSON serializable version of the remaining input to read.
3.857345
3.654194
1.055594
params = _get_params(mapper_spec) shard_count = mapper_spec.shard_count # Pick out the overall start and end times and time step per shard. start_time = params[cls.START_TIME_PARAM] end_time = params[cls.END_TIME_PARAM] seconds_per_shard = (end_time - start_time) / shard_count # Creat...
def split_input(cls, mapper_spec)
Returns a list of input readers for the given input specification. Args: mapper_spec: The MapperSpec for this InputReader. Returns: A list of InputReaders.
2.797067
2.934412
0.953195
if mapper_spec.input_reader_class() != cls: raise errors.BadReaderParamsError("Input reader class mismatch") params = _get_params(mapper_spec, allowed_keys=cls._PARAMS) if (cls.VERSION_IDS_PARAM not in params and cls.MODULE_VERSIONS_PARAM not in params): raise errors.BadReaderParam...
def validate(cls, mapper_spec)
Validates the mapper's specification and all necessary parameters. Args: mapper_spec: The MapperSpec to be used with this InputReader. Raises: BadReaderParamsError: If the user fails to specify both a starting time and an ending time, or if the starting time is later than the ending ...
3.142161
3.080069
1.020159
while True: if self._bucket_iter: try: return self._bucket_iter.next().filename except StopIteration: self._bucket_iter = None self._bucket = None if self._index >= len(self._filenames): return filename = self._filenames[self._index] ...
def _next_file(self)
Find next filename. self._filenames may need to be expanded via listbucket. Returns: None if no more file is left. Filename otherwise.
2.63775
2.492519
1.058267
reader_spec = cls.get_params(mapper_spec, allow_old=False) # Bucket Name is required if cls.BUCKET_NAME_PARAM not in reader_spec: raise errors.BadReaderParamsError( "%s is required for Google Cloud Storage" % cls.BUCKET_NAME_PARAM) try: cloudstorage.validate_bucket_...
def validate(cls, mapper_spec)
Validate mapper specification. Args: mapper_spec: an instance of model.MapperSpec Raises: BadReaderParamsError: if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name.
1.983232
1.940754
1.021887
reader_spec = cls.get_params(mapper_spec, allow_old=False) bucket = reader_spec[cls.BUCKET_NAME_PARAM] filenames = reader_spec[cls.OBJECT_NAMES_PARAM] delimiter = reader_spec.get(cls.DELIMITER_PARAM) account_id = reader_spec.get(cls._ACCOUNT_ID_PARAM) buffer_size = reader_spec.get(cls.BUFFE...
def split_input(cls, mapper_spec)
Returns a list of input readers. An equal number of input files are assigned to each shard (+/- 1). If there are fewer files than shards, fewer than the requested number of shards will be used. Input files are currently never split (although for some formats could be and may be split in a future implem...
2.684224
2.650529
1.012713
options = {} if self._buffer_size: options["read_buffer_size"] = self._buffer_size if self._account_id: options["_account_id"] = self._account_id while True: filename = self._next_file() if filename is None: raise StopIteration() try: start_time = time....
def next(self)
Returns the next input from this input reader, a block of bytes. Non existent files will be logged and skipped. The file might have been removed after input splitting. Returns: The next input from this input reader in the form of a cloudstorage ReadBuffer that supports a File-like interface (r...
4.854288
4.268618
1.137204
while True: if not hasattr(self, "_cur_handle") or self._cur_handle is None: # If there are no more files, StopIteration is raised here self._cur_handle = super(_GoogleCloudStorageRecordInputReader, self).next() if not hasattr(self, "_record_reader")...
def next(self)
Returns the next input from this input reader, a record. Returns: The next input from this input reader in the form of a record read from an LevelDB file. Raises: StopIteration: The ordered set records has been exhausted.
3.614406
3.441854
1.050133
result = super(_ReducerReader, self).to_json() result["current_key"] = self.encode_data(self.current_key) result["current_values"] = self.encode_data(self.current_values) return result
def to_json(self)
Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader.
5.095889
4.732881
1.076699
result = super(_ReducerReader, cls).from_json(json) result.current_key = _ReducerReader.decode_data(json["current_key"]) result.current_values = _ReducerReader.decode_data(json["current_values"]) return result
def from_json(cls, json)
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.
4.685957
4.8184
0.972513
self._state.counters_map.increment(counter_name, delta)
def incr(self, counter_name, delta=1)
Changes counter by delta. Args: counter_name: the name of the counter to change. str. delta: int.
15.465787
15.195013
1.01782
return self._state.counters_map.get(counter_name, default)
def counter(self, counter_name, default=0)
Get the current counter value. Args: counter_name: name of the counter in string. default: default value in int if one doesn't exist. Returns: Current value of the counter.
9.667696
14.283736
0.676832
if not self._tstate.output_writer: logging.error("emit is called, but no output writer is set.") return self._tstate.output_writer.write(value)
def emit(self, value)
Emits a value to output writer. Args: value: a value of type expected by the output writer.
6.086761
5.308145
1.146683
reader_params = job_config.input_reader_params # Bucket Name is required if cls.BUCKET_NAME_PARAM not in reader_params: raise errors.BadReaderParamsError( "%s is required for Google Cloud Storage" % cls.BUCKET_NAME_PARAM) try: cloudstorage.validate_bucket_name( ...
def validate(cls, job_config)
Validate mapper specification. Args: job_config: map_job.JobConfig. Raises: BadReaderParamsError: if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name.
1.696219
1.674413
1.013023
reader_params = job_config.input_reader_params bucket = reader_params[cls.BUCKET_NAME_PARAM] filenames = reader_params[cls.OBJECT_NAMES_PARAM] delimiter = reader_params.get(cls.DELIMITER_PARAM) account_id = reader_params.get(cls._ACCOUNT_ID_PARAM) buffer_size = reader_params.get(cls.BUFFER_...
def split_input(cls, job_config)
Returns a list of input readers. An equal number of input files are assigned to each shard (+/- 1). If there are fewer files than shards, fewer than the requested number of shards will be used. Input files are currently never split (although for some formats could be and may be split in a future implem...
2.599777
2.621098
0.991866
options = {} if self._buffer_size: options["read_buffer_size"] = self._buffer_size if self._account_id: options["_account_id"] = self._account_id while True: filename = self._next_file() if filename is None: raise StopIteration() if (self._path_filter and ...
def next(self)
Returns a handler to the next file. Non existent files will be logged and skipped. The file might have been removed after input splitting. Returns: The next input from this input reader in the form of a cloudstorage ReadBuffer that supports a File-like interface (read, readline, seek, te...
3.294084
2.916275
1.129552
params_cp = dict(params) if cls.PATH_FILTER_PARAM in params_cp: path_filter = params_cp[cls.PATH_FILTER_PARAM] params_cp[cls.PATH_FILTER_PARAM] = pickle.dumps(path_filter) return params_cp
def params_to_json(cls, params)
Inherit docs.
3.203947
3.089776
1.036951
while True: if not hasattr(self, "_cur_handle") or self._cur_handle is None: # If there are no more files, StopIteration is raised here self._cur_handle = super(GCSRecordInputReader, self).next() if not hasattr(self, "_record_reader") or self._record_reader is None: self._re...
def next(self)
Returns the next input from this input reader, a record. Returns: The next input from this input reader in the form of a record read from an LevelDB file. Raises: StopIteration: The ordered set records has been exhausted.
3.355613
3.212868
1.044429
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.KEYS_ONLY_PARAM, Fa...
def _get_query_spec(cls, params)
Construct a model.QuerySpec from model.MapperSpec.
2.814272
2.58446
1.088921
shard_count = job_config.shard_count params = job_config.input_reader_params query_spec = cls._get_query_spec(params) 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: ...
def split_input(cls, job_config)
Inherit doc.
4.379879
4.356047
1.005471
key_ranges_by_ns = [] # Split each ns into n splits. If a ns doesn't have enough scatter to # split into n, the last few splits are None. for namespace in namespaces: ranges = cls._split_ns_by_scatter( shard_count, namespace, query_spec.entity_kind, app...
def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec)
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_spe...
4.356113
4.262007
1.02208
if shard_count == 1: # With one shard we don't need to calculate any split points at all. return [key_range.KeyRange(namespace=namespace, _app=app)] ds_query = datastore.Query(kind=raw_entity_kind, namespace=namespace, _app=app, ...
def _split_ns_by_scatter(cls, shard_count, namespace, raw_entity_kind, app)
Split a namespace by scatter index into key_range.KeyRange. TODO(user): Power this with key_range.KeyRange.compute_split_points. 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. ...
2.342886
2.233337
1.049052
super(AbstractDatastoreInputReader, cls).validate(job_config) params = job_config.input_reader_params # Check for the required entity kind parameter. if cls.ENTITY_KIND_PARAM not in params: raise errors.BadReaderParamsError("Missing input reader parameter " ...
def validate(cls, job_config)
Inherit docs.
2.081345
2.045616
1.017466
global NAMESPACE_CHARACTERS global MAX_NAMESPACE_LENGTH # pylint: disable=global-variable-undefined global MAX_NAMESPACE global _LEX_DISTANCE global NAMESPACE_BATCH_SIZE NAMESPACE_CHARACTERS = alphabet MAX_NAMESPACE_LENGTH = max_length MAX_NAMESPACE = NAMESPACE_CHARACTERS[-1] * MAX_NAMESPACE_LENG...
def _setup_constants(alphabet=NAMESPACE_CHARACTERS, max_length=MAX_NAMESPACE_LENGTH, batch_size=NAMESPACE_BATCH_SIZE)
Calculate derived constant values. Only useful for testing.
2.505719
2.487437
1.00735
if _max_length is None: _max_length = MAX_NAMESPACE_LENGTH length = _LEX_DISTANCE[_max_length - 1] if n == 0: return '' n -= 1 return (NAMESPACE_CHARACTERS[n / length] + _ord_to_namespace(n % length, _max_length - 1))
def _ord_to_namespace(n, _max_length=None)
Convert a namespace ordinal to a namespace string. Converts an int, representing the sequence number of a namespace ordered lexographically, into a namespace string. >>> _ord_to_namespace(0) '' >>> _ord_to_namespace(1) '-' >>> _ord_to_namespace(2) '--' >>> _ord_to_namespace(3) '---' Args: n...
4.20196
4.483612
0.937182