desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Constructor for reverse reference. Constructor does not take standard values of other property types. Args: model: Model class that this property is a collection of. property: Name of foreign property on referred model that points back to this properties entity.'
def __init__(self, model, prop):
self.__model = model self.__property = prop
'Internal helper to access the model class, read-only.'
@property def _model(self):
return self.__model
'Internal helper to access the property name, read-only.'
@property def _prop_name(self):
return self.__property
'Fetches collection of model instances of this collection property.'
def __get__(self, model_instance, model_class):
if (model_instance is not None): query = Query(self.__model) return query.filter((self.__property + ' ='), model_instance.key()) else: return self
'Not possible to set a new collection.'
def __set__(self, model_instance, value):
raise BadValueError('Virtual property is read-only')
'Constructor. Args: value_function: Callable f(model_instance) -> value used to derive persistent property value for storage in datastore. indexed: Whether or not the attribute should be indexed.'
def __init__(self, value_function, indexed=True):
super(ComputedProperty, self).__init__(indexed=indexed) self.__value_function = value_function
'Disallow setting this value. Raises: DerivedPropertyError when developer attempts to set attribute manually. Model knows to ignore this exception when getting from datastore.'
def __set__(self, *args):
raise DerivedPropertyError(('Computed property %s cannot be set.' % self.name))
'Derive property value. Args: model_instance: Instance to derive property for in bound method case, else None. model_class: Model class associated with this property descriptor. Returns: Result of calling self.__value_funcion as provided by property constructor.'
def __get__(self, model_instance, model_class):
if (model_instance is None): return self return self.__value_function(model_instance)
'Kind name override.'
@classmethod def kind(cls):
return cls.KIND_NAME
'Return the namespace name specified by this entity\'s key.'
@property def namespace_name(self):
return self.key_to_namespace(self.key())
'Return the __namespace__ key for namespace. Args: namespace: namespace whose key is requested. Returns: The key for namespace.'
@classmethod def key_for_namespace(cls, namespace):
if namespace: return db.Key.from_path(cls.KIND_NAME, namespace) else: return db.Key.from_path(cls.KIND_NAME, cls.EMPTY_NAMESPACE_ID)
'Return the namespace specified by a given __namespace__ key. Args: key: key whose name is requested. Returns: The namespace specified by key.'
@classmethod def key_to_namespace(cls, key):
return (key.name() or '')
'Return the kind name specified by this entity\'s key.'
@property def kind_name(self):
return self.key_to_kind(self.key())
'Return the __kind__ key for kind. Args: kind: kind whose key is requested. Returns: The key for kind.'
@classmethod def key_for_kind(cls, kind):
return db.Key.from_path(cls.KIND_NAME, kind)
'Return the kind specified by a given __kind__ key. Args: key: key whose name is requested. Returns: The kind specified by key.'
@classmethod def key_to_kind(cls, key):
return key.name()
'Return the property name specified by this entity\'s key.'
@property def property_name(self):
return self.key_to_property(self.key())
'Return the kind name specified by this entity\'s key.'
@property def kind_name(self):
return self.key_to_kind(self.key())
'Return the __property__ key for kind. Args: kind: kind whose key is requested. Returns: The parent key for __property__ keys of kind.'
@classmethod def key_for_kind(cls, kind):
return db.Key.from_path(Kind.KIND_NAME, kind)
'Return the __property__ key for property of kind. Args: kind: kind whose key is requested. property: property whose key is requested. Returns: The key for property of kind.'
@classmethod def key_for_property(cls, kind, property):
return db.Key.from_path(Kind.KIND_NAME, kind, Property.KIND_NAME, property)
'Return the kind specified by a given __property__ key. Args: key: key whose kind name is requested. Returns: The kind specified by key.'
@classmethod def key_to_kind(cls, key):
if (key.kind() == Kind.KIND_NAME): return key.name() else: return key.parent().name()
'Return the property specified by a given __property__ key. Args: key: key whose property name is requested. Returns: property specified by key, or None if the key specified only a kind.'
@classmethod def key_to_property(cls, key):
if (key.kind() == Kind.KIND_NAME): return None else: return key.name()
'Return the metadata key for the entity group containing entity_or_key. Use this key to get() the __entity_group__ metadata entity for the entity group containing entity_or_key. Args: entity_or_key: a key or entity whose __entity_group__ key you want. Returns: The __entity_group__ key for the entity group containing en...
@classmethod def key_for_entity(cls, entity_or_key):
if isinstance(entity_or_key, db.Model): key = entity_or_key.key() else: key = entity_or_key while key.parent(): key = key.parent() return db.Key.from_path(cls.KIND_NAME, cls.ID, parent=key)
'Initializes a class that belongs to a polymorphic hierarchy. This method configures a few built-in attributes of polymorphic models: __root_class__: If the new class is a root class, __root_class__ is set to itself so that it subclasses can quickly know what the root of their hierarchy is and what kind they are stored...
def __init__(cls, name, bases, dct):
if (name == 'PolyModel'): super(PolymorphicClass, cls).__init__(name, bases, dct, map_kind=False) return elif (PolyModel in bases): if getattr(cls, '__class_hierarchy__', None): raise db.ConfigurationError(('%s cannot derive from PolyModel as __class_hierarc...
'Prevents direct instantiation of PolyModel. Allow subclasses to call __new__() with arguments. Do NOT list \'cls\' as the first argument, or in the case when the \'kwds\' dictionary contains the key \'cls\', the function will complain about multiple argument values for \'cls\'. Raises: TypeError if there are no positi...
def __new__(*args, **kwds):
if args: cls = args[0] else: raise TypeError('object.__new__(): not enough arguments') if (cls is PolyModel): raise NotImplementedError() return super(PolyModel, cls).__new__(cls, *args, **kwds)
'Get kind of polymorphic model. Overridden so that all subclasses of root classes are the same kind as the root. Returns: Kind of entity to write to datastore.'
@classmethod def kind(cls):
if (cls is cls.__root_class__): return super(PolyModel, cls).kind() else: return cls.__root_class__.kind()
'Caclulate the class-key for this class. Returns: Class key for class. By default this is a the list of classes of the hierarchy, starting with the root class and walking its way down to cls.'
@classmethod def class_key(cls):
if (not hasattr(cls, '__class_hierarchy__')): raise NotImplementedError('Cannot determine class key without class hierarchy') return tuple((cls.class_name() for cls in cls.__class_hierarchy__))
'Calculate class name for this class. Returns name to use for each classes element within its class-key. Used to discriminate between different classes within a class hierarchy\'s Datastore kind. The presence of this method allows developers to use a different class name in the datastore from what is used in Python co...
@classmethod def class_name(cls):
return cls.__name__
'Load from entity to class based on discriminator. Rather than instantiating a new Model instance based on the kind mapping, this creates an instance of the correct model class based on the entities class-key. Args: entity: Entity loaded directly from datastore. Raises: KindError when there is no class mapping based on...
@classmethod def from_entity(cls, entity):
if ((_CLASS_KEY_PROPERTY in entity) and (tuple(entity[_CLASS_KEY_PROPERTY]) != cls.class_key())): key = tuple(entity[_CLASS_KEY_PROPERTY]) try: poly_class = _class_map[key] except KeyError: raise db.KindError(("No implementation for class '%s'" % (key,))) ...
'Get all instance of a class hierarchy. Args: kwds: Keyword parameters passed on to Model.all. Returns: Query with filter set to match this class\' discriminator.'
@classmethod def all(cls, **kwds):
query = super(PolyModel, cls).all(**kwds) if (cls != cls.__root_class__): query.filter((_CLASS_KEY_PROPERTY + ' ='), cls.class_name()) return query
'Returns a polymorphic query using GQL query string. This query is polymorphic in that it has its filters configured in a way to retrieve instances of the model or an instance of a subclass of the model. Args: query_string: properly formatted GQL query string with the \'SELECT * FROM <entity>\' part omitted *args: rest...
@classmethod def gql(cls, query_string, *args, **kwds):
if (cls == cls.__root_class__): return super(PolyModel, cls).gql(query_string, *args, **kwds) else: from google.appengine.ext import gql query = db.GqlQuery(('SELECT * FROM %s %s' % (cls.kind(), query_string))) query_filter = [('nop', [gql.Literal(cls.class_name())])]...
'Kind name override.'
@classmethod def kind(cls):
return cls.STORED_KIND_NAME
'Return a Django form field appropriate for this property. Args: form_class: a forms.Field subclass, default forms.CharField Additional keyword arguments are passed to the form_class constructor, with certain defaults: required: self.required label: prettified self.verbose_name, if not None widget: a forms.Select insta...
def get_form_field(self, form_class=forms.CharField, **kwargs):
defaults = {'required': self.required} if self.verbose_name: defaults['label'] = self.verbose_name.capitalize().replace('_', ' ') if self.choices: choices = [] if ((not self.required) or ((self.default is None) and ('initial' not in kwargs))): choices.append(('', '----...
'Extract the property value from the instance for use in a form. Override this to do a property- or field-specific type conversion. Args: instance: a db.Model instance Returns: The property\'s value extracted from the instance, possibly converted to a type suitable for a form field; possibly None. By default this retur...
def get_value_for_form(self, instance):
return getattr(instance, self.name)
'Convert a form value to a property value. Override this to do a property- or field-specific type conversion. Args: value: the cleaned value retrieved from the form field Returns: A value suitable for assignment to a model instance\'s property; possibly None. By default this converts the value to self.data_type if it i...
def make_value_from_form(self, value):
if (value in (None, '')): return None if (not isinstance(value, self.data_type)): value = self.data_type(value) return value
'Return a Django form field appropriate for a User property. This defaults to a forms.EmailField instance, except if auto_current_user or auto_current_user_add is set, in which case None is returned, as such \'auto\' fields should not be rendered as part of the form.'
def get_form_field(self, **kwargs):
if (self.auto_current_user or self.auto_current_user_add): return None defaults = {'form_class': forms.EmailField} defaults.update(kwargs) return super(UserProperty, self).get_form_field(**defaults)
'Extract the property value from the instance for use in a form. This returns the email address of the User.'
def get_value_for_form(self, instance):
value = super(UserProperty, self).get_value_for_form(instance) if (not value): return None return value.email()
'Return a Django form field appropriate for a string property. This sets the widget default to forms.Textarea if the property\'s multiline attribute is set.'
def get_form_field(self, **kwargs):
defaults = {} if self.multiline: defaults['widget'] = forms.Textarea defaults.update(kwargs) return super(StringProperty, self).get_form_field(**defaults)
'Return a Django form field appropriate for a text property. This sets the widget default to forms.Textarea.'
def get_form_field(self, **kwargs):
defaults = {'widget': forms.Textarea} defaults.update(kwargs) return super(TextProperty, self).get_form_field(**defaults)
'Return a Django form field appropriate for a blob property. This defaults to a forms.FileField instance when using Django 0.97 or later. For 0.96 this returns None, as file uploads are not really supported in that version.'
def get_form_field(self, **kwargs):
if (not hasattr(forms, 'FileField')): return None defaults = {'form_class': forms.FileField} defaults.update(kwargs) return super(BlobProperty, self).get_form_field(**defaults)
'Extract the property value from the instance for use in a form. There is no way to convert a Blob into an initial value for a file upload, so we always return None.'
def get_value_for_form(self, instance):
return None
'Convert a form value to a property value. This extracts the content from the UploadedFile instance returned by the FileField instance.'
def make_value_from_form(self, value):
if (have_uploadedfile and isinstance(value, uploadedfile.UploadedFile)): if (not self.form_value): self.form_value = value.read() b = db.Blob(self.form_value) return b return super(BlobProperty, self).make_value_from_form(value)
'Return a Django form field appropriate for a date-time property. This defaults to a DateTimeField instance, except if auto_now or auto_now_add is set, in which case None is returned, as such \'auto\' fields should not be rendered as part of the form.'
def get_form_field(self, **kwargs):
if (self.auto_now or self.auto_now_add): return None defaults = {'form_class': forms.DateTimeField} defaults.update(kwargs) return super(DateTimeProperty, self).get_form_field(**defaults)
'Return a Django form field appropriate for a date property. This defaults to a DateField instance, except if auto_now or auto_now_add is set, in which case None is returned, as such \'auto\' fields should not be rendered as part of the form.'
def get_form_field(self, **kwargs):
if (self.auto_now or self.auto_now_add): return None defaults = {'form_class': forms.DateField} defaults.update(kwargs) return super(DateProperty, self).get_form_field(**defaults)
'Return a Django form field appropriate for a time property. This defaults to a TimeField instance, except if auto_now or auto_now_add is set, in which case None is returned, as such \'auto\' fields should not be rendered as part of the form.'
def get_form_field(self, **kwargs):
if (self.auto_now or self.auto_now_add): return None defaults = {'form_class': forms.TimeField} defaults.update(kwargs) return super(TimeProperty, self).get_form_field(**defaults)
'Return a Django form field appropriate for an integer property. This defaults to an IntegerField instance.'
def get_form_field(self, **kwargs):
defaults = {'form_class': forms.IntegerField} defaults.update(kwargs) return super(IntegerProperty, self).get_form_field(**defaults)
'Return a Django form field appropriate for an integer property. This defaults to a FloatField instance when using Django 0.97 or later. For 0.96 this defaults to the CharField class.'
def get_form_field(self, **kwargs):
defaults = {} if hasattr(forms, 'FloatField'): defaults['form_class'] = forms.FloatField defaults.update(kwargs) return super(FloatProperty, self).get_form_field(**defaults)
'Return a Django form field appropriate for a boolean property. This defaults to a BooleanField.'
def get_form_field(self, **kwargs):
defaults = {'form_class': forms.BooleanField} defaults.update(kwargs) return super(BooleanProperty, self).get_form_field(**defaults)
'Convert a form value to a property value. This is needed to ensure that False is not replaced with None.'
def make_value_from_form(self, value):
if (value is None): return None if (isinstance(value, basestring) and (value.lower() == 'false')): return False return bool(value)
'Return a Django form field appropriate for a StringList property. This defaults to a Textarea widget with a blank initial value.'
def get_form_field(self, **kwargs):
defaults = {'widget': forms.Textarea, 'initial': ''} defaults.update(kwargs) return super(StringListProperty, self).get_form_field(**defaults)
'Extract the property value from the instance for use in a form. This joins a list of strings with newlines.'
def get_value_for_form(self, instance):
value = super(StringListProperty, self).get_value_for_form(instance) if (not value): return None if isinstance(value, list): value = '\n'.join(value) return value
'Convert a form value to a property value. This breaks the string into lines.'
def make_value_from_form(self, value):
if (not value): return [] if isinstance(value, basestring): value = value.splitlines() return value
'Return a Django form field appropriate for a URL property. This defaults to a URLField instance.'
def get_form_field(self, **kwargs):
defaults = {'form_class': forms.URLField} defaults.update(kwargs) return super(LinkProperty, self).get_form_field(**defaults)
'Constructor. Args: reference_class: required; the db.Model subclass used in the reference query: optional db.Query; default db.Query(reference_class) choices: optional explicit list of (value, label) pairs representing available choices; defaults to dynamically iterating over the query argument (or its default) empty_...
def __init__(self, reference_class, query=None, choices=None, empty_label=u'---------', required=True, widget=forms.Select, label=None, initial=None, help_text=None, *args, **kwargs):
assert issubclass(reference_class, db.Model) if (query is None): query = db.Query(reference_class) assert isinstance(query, db.Query) super(ModelChoiceField, self).__init__(required, widget, label, initial, help_text, *args, **kwargs) self.empty_label = empty_label self.reference_class =...
'Helper to copy the choices to the widget.'
def _update_widget_choices(self):
self.widget.choices = self.choices
'Getter for the query attribute.'
def _get_query(self):
return self._query
'Setter for the query attribute. As a side effect, the widget\'s choices are updated.'
def _set_query(self, query):
self._query = query self._update_widget_choices()
'Generator yielding (key, label) pairs from the query results.'
def _generate_choices(self):
(yield ('', self.empty_label)) for inst in self._query: (yield (inst.key(), unicode(inst)))
'Getter for the choices attribute. This is required to return an object that can be iterated over multiple times.'
def _get_choices(self):
if (self._choices is not None): return self._choices return _WrapIter(self._generate_choices)
'Setter for the choices attribute. As a side effect, the widget\'s choices are updated.'
def _set_choices(self, choices):
self._choices = choices self._update_widget_choices()
'Override Field.clean() to do reference-specific value cleaning. This turns a non-empty value into a model instance.'
def clean(self, value):
value = super(ModelChoiceField, self).clean(value) if (not value): return None instance = db.get(value) if (instance is None): raise db.BadValueError(self.error_messages['invalid_choice']) return instance
'Return a Django form field appropriate for a reference property. This defaults to a ModelChoiceField instance.'
def get_form_field(self, **kwargs):
defaults = {'form_class': ModelChoiceField, 'reference_class': self.reference_class} defaults.update(kwargs) return super(ReferenceProperty, self).get_form_field(**defaults)
'Extract the property value from the instance for use in a form. This return the key object for the referenced object, or None.'
def get_value_for_form(self, instance):
value = super(ReferenceProperty, self).get_value_for_form(instance) if (value is not None): value = value.key() return value
'Convert a form value to a property value. This turns a key string or object into a model instance.'
def make_value_from_form(self, value):
if value: if (not isinstance(value, db.Model)): value = db.get(value) return value
'Return a Django form field appropriate for a reverse reference. This always returns None, since reverse references are always automatic.'
def get_form_field(self, **kwargs):
return None
'Constructor for a new ModelForm class instance. The signature of this method is determined by Python internals. All Django Field instances are removed from attrs and added to the base_fields attribute instead. Additional Field instances are added to this based on the Datastore Model class specified by the Meta attrib...
def __new__(cls, class_name, bases, attrs):
fields = sorted(((field_name, attrs.pop(field_name)) for (field_name, obj) in attrs.items() if isinstance(obj, forms.Field)), key=(lambda obj: obj[1].creation_counter)) for base in bases[::(-1)]: if hasattr(base, 'base_fields'): fields = (base.base_fields.items() + fields) declared_field...
'Constructor. Args (all optional and defaulting to None): data: dict of data values, typically from a POST request) files: dict of file upload values; Django 0.97 or later only auto_id, prefix: see Django documentation initial: dict of initial values error_class, label_suffix: see Django 0.97 or later documentation ins...
def __init__(self, data=None, files=None, auto_id=None, prefix=None, initial=None, error_class=None, label_suffix=None, instance=None):
opts = self._meta self.instance = instance object_data = {} if (instance is not None): for (name, prop) in instance.properties().iteritems(): if (opts.fields and (name not in opts.fields)): continue if (opts.exclude and (name in opts.exclude)): ...
'Save this form\'s cleaned data into a model instance. Args: commit: optional bool, default True; if true, the model instance is also saved to the datastore. Returns: A model instance. If a model instance was already associated with this form instance (either passed to the constructor with instance=... or by a previo...
def save(self, commit=True):
if (not self.is_bound): raise ValueError('Cannot save an unbound form') opts = self._meta instance = self.instance if (instance is None): fail_message = 'created' else: fail_message = 'updated' if self.errors: raise ValueError(("The %s could n...
'Helper to retrieve the cleaned data attribute. In Django 0.96 this attribute was called self.clean_data. In 0.97 and later it\'s been renamed to self.cleaned_data, to avoid a name conflict. This helper abstracts the difference between the versions away from its caller.'
def _cleaned_data(self):
try: return self.cleaned_data except AttributeError: return self.clean_data
'Returns entity kind.'
@classmethod def kind(cls):
return '_GAE_MR_OutputFile'
'Get root key to store output files. Args: job_id: pipeline\'s job id. Returns: root key for a given job id to store output file entities.'
@classmethod def get_root_key(cls, job_id):
return db.Key.from_path(cls.kind(), job_id)
'Constructor. Args: offsets: offsets for each input file to start from as list of ints. max_values_count: maximum number of values to yield for a single value at a time. Ignored if -1. max_values_size: maximum total size of yielded values. Ignored if -1'
def __init__(self, offsets, max_values_count, max_values_size):
self._offsets = offsets self._max_values_count = max_values_count self._max_values_size = max_values_size
'Iterate over records in input files. self._offsets is always correctly updated so that stopping iterations doesn\'t skip records and doesn\'t read the same record twice.'
def __iter__(self):
ctx = context.get() mapper_spec = ctx.mapreduce_spec.mapper shard_number = ctx.shard_state.shard_number filenames = mapper_spec.params[self.FILES_PARAM][shard_number] if (len(filenames) != len(self._offsets)): raise Exception('Files list and offsets do not match.') read...
'Restore reader from json state.'
@classmethod def from_json(cls, json):
return cls(json['offsets'], json['max_values_count'], json['max_values_size'])
'Serialize reader state to json.'
def to_json(self):
return {'offsets': self._offsets, 'max_values_count': self._max_values_count, 'max_values_size': self._max_values_size}
'Split input into multiple shards.'
@classmethod def split_input(cls, mapper_spec):
filelists = mapper_spec.params[cls.FILES_PARAM] max_values_count = mapper_spec.params.get(cls.MAX_VALUES_COUNT_PARAM, (-1)) max_values_size = mapper_spec.params.get(cls.MAX_VALUES_SIZE_PARAM, (-1)) return [cls(([0] * len(files)), max_values_count, max_values_size) for files in filelists]
'Validate reader parameters in mapper_spec.'
@classmethod def validate(cls, mapper_spec):
if (mapper_spec.input_reader_class() != cls): raise errors.BadReaderParamsError('Input reader class mismatch') params = mapper_spec.params if (not (cls.FILES_PARAM in params)): raise errors.BadReaderParamsError('Missing files parameter.')
'Constructor. Args: filenames: list of filenames that this writer outputs to.'
def __init__(self, filenames):
self._filenames = filenames
'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')
'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):
shards = mapreduce_state.mapreduce_spec.mapper.shard_count filenames = [] for i in range(shards): blob_file_name = ((((mapreduce_state.mapreduce_spec.name + '-') + mapreduce_state.mapreduce_spec.mapreduce_id) + '-output-') + str(i)) filenames.append(files.blobstore.create(_blobinfo_uploaded_...
'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):
finalized_filenames = [] for filename in mapreduce_state.writer_state['filenames']: files.finalize(filename) finalized_filenames.append(files.blobstore.get_file_name(files.blobstore.get_blob_key(filename))) mapreduce_state.writer_state = {'filenames': finalized_filenames}
'Creates an instance of the OutputWriter for the given json state. Args: json: 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, json):
return cls(json['filenames'])
'Returns writer state to serialize in json. Returns: A json-izable version of the OutputWriter state.'
def to_json(self):
return {'filenames': self._filenames}
'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):
return cls(mapreduce_state.writer_state['filenames'])
'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):
return mapreduce_state.writer_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 (len(data) != 2): logging.error('Got bad tuple of length %d (2-tuple expected): %s', len(data), data) try: key = str(data[0]) value = str(data[1]) except TypeError: logging.error('Expecting a tuple, but got %s: %s', data.__class__....
'Constructor.'
def __init__(self, *args):
super(MapperWorkerCallbackHandler, self).__init__(*args) self._time = time.time
'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: True if lease is acquired. False if this ...
def _try_acquire_lease(self, shard_state, tstate):
if (not shard_state): logging.warning('State not found for shard %s; Possible spurious task execution. Dropping this task.', tstate.shard_id) return False if (not shard_state.active): logging.warning('Shard %s is not active. Possible ...
'Whether previous slice retry has ended. Args: shard_state: shard state. Returns: True if the request of previous slice retry has ended. False if it has not or unknown.'
def _old_request_ended(self, shard_state):
assert (shard_state.slice_start_time is not None) assert (shard_state.slice_request_id is not None) logs = list(logservice.fetch(request_ids=[shard_state.slice_request_id])) if ((not logs) or (not logs[0].finished)): return False return True
'Number of seconds before lease expire.'
def _lease_countdown(self, shard_state):
assert (shard_state.slice_start_time is not None) delta = (datetime.datetime.now() - shard_state.slice_start_time) min_delta = datetime.timedelta(seconds=(_SLICE_DURATION_SEC + _LEASE_GRACE_PERIOD)) if (delta < min_delta): return int(math.ceil((min_delta - delta).total_seconds())) else: ...
'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 updates/saves shard sta...
def _try_free_lease(self, shard_state, slice_retry=False):
@db.transactional def _tx(): fresh_state = model.ShardState.get_by_shard_id(shard_state.shard_id) if (fresh_state and fresh_state.active and (fresh_state.slice_id == shard_state.slice_id)): fresh_state.slice_start_time = None fresh_state.slice_request_id = None ...
'Handle request.'
def handle(self):
tstate = model.TransientShardState.from_request(self.request) spec = tstate.mapreduce_spec self._start_time = self._time() (shard_state, control) = db.get([model.ShardState.get_key_by_shard_id(tstate.shard_id), model.MapreduceControl.get_key_by_job_id(spec.mapreduce_id)]) if (not self._try_acquire_l...
'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 False. If errors.F...
def process_inputs(self, input_reader, shard_state, tstate, ctx):
processing_limit = self._processing_limit(tstate.mapreduce_spec) if (processing_limit == 0): return finished_shard = True for entity in input_reader: if isinstance(entity, db.Model): shard_state.last_work_item = repr(entity.key()) elif (ndb and isinstance(entity, ndb....
'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.'
def process_data(self, data, input_reader, ctx, transient_shard_state):
if (data is not input_readers.ALLOW_CHECKPOINT): ctx.counters.increment(context.COUNTER_MAPPER_CALLS) handler = transient_shard_state.handler if input_reader.expand_parameters: result = handler(*data) else: result = handler(data) if util.is_generator(r...
'Save state to datastore and schedule next task for this shard. Update and save shard state. Schedule next slice if needed. This method handles interactions with datastore and taskqueue. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. retry_shard: whether to r...
def _save_state_and_schedule_next(self, shard_state, tstate, retry_shard):
spec = tstate.mapreduce_spec config = util.create_datastore_write_config(spec) task = None if retry_shard: task = self._state_to_task(tstate) elif shard_state.active: shard_state.advance_for_next_slice() tstate.advance_for_next_slice() countdown = self._get_countdown_...
'Handle retry for this slice. This method may modify shard_state and tstate to prepare for retry or fail. Args: e: the exception caught. shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. mr_id: mapreduce id. Returns: True if shard should be retried. False otherwise. R...
def _retry_logic(self, e, shard_state, tstate, mr_id):
logging.error('Shard %s got error.', shard_state.shard_id) logging.error(traceback.format_exc()) if (type(e) is errors.FailJobError): logging.error('Got FailJobError. Shard %s failed permanently.', shard_state.shard_id) shard_state.active = False shard_state.r...
'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. mr_id: mapreduce id. Returns: True if shard should be retried. False otherwise.'
def _attempt_shard_retry(self, shard_state, tstate, mr_id):
shard_retry = shard_state.retries permanent_shard_failure = False if (shard_retry >= parameters.DEFAULT_SHARD_RETRY_LIMIT): logging.error('Shard has been retried %s times. Shard %s will fail permanently.', shard_retry, shard_state.shard_id) permanent_shard_failu...
'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: False when slice can\'t be retried anymore. Raises: errors.RetrySliceError: in order to trigger a...
def _attempt_slice_retry(self, shard_state, tstate):
if (shard_state.slice_retries < _RETRY_SLICE_ERROR_MAX_RETRIES): logging.error('Will retry slice %s %s for the %s time.', tstate.shard_id, tstate.slice_id, (self.task_retry_count() + 1)) sys.exc_clear() self._try_free_lease(shard_state, slice_retry=True) raise...
'Compute single worker task name. Args: shard_id: shard id. slice_id: slice id. retry: current shard retry count. Returns: task name which should be used to process specified shard/slice.'
@staticmethod def get_task_name(shard_id, slice_id, retry=0):
return ('appengine-mrshard-%s-%s-retry-%s' % (shard_id, slice_id, retry))
'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.'
def _get_countdown_for_next_slice(self, spec):
countdown = 0 if (self._processing_limit(spec) != (-1)): countdown = max(int((_SLICE_DURATION_SEC - (self._time() - self._start_time))), 0) return countdown
'Generate task for slice according to current states. Args: tstate: An instance of TransientShardState. eta: Absolute time when the MR should execute. May not be specified if \'countdown\' is also supplied. This may be timezone-aware or timezone-naive. countdown: Time in seconds into the future that this MR should exec...
@classmethod def _state_to_task(cls, tstate, eta=None, countdown=None):
base_path = tstate.base_path task_name = MapperWorkerCallbackHandler.get_task_name(tstate.shard_id, tstate.slice_id, tstate.retries) worker_task = util.HugeTask(url=(base_path + '/worker_callback'), params=tstate.to_dict(), name=task_name, eta=eta, countdown=countdown) return worker_task