Exemplo n.º 1
0
 def AcquireLock(cls, client, viewpoint_id, callback):
     """Acquires a persistent global lock on the specified viewpoint."""
     op = Operation.GetCurrent()
     lock = yield gen.Task(Lock.Acquire, client, LockResourceType.Viewpoint,
                           viewpoint_id, op.operation_id)
     ViewpointLockTracker.AddViewpointId(viewpoint_id)
     callback(lock)
Exemplo n.º 2
0
  def TerminateAccountOperation(cls, client, user_id, merged_with=None):
    """Invokes User.TerminateAccount via operation execution."""
    @gen.coroutine
    def _VisitIdentity(identity_key):
      """Unlink this identity from the user."""
      yield Identity.UnlinkIdentityOperation(client, user_id, identity_key.hash_key)

    # Turn off alerts to all devices owned by the user.
    yield gen.Task(Device.MuteAlerts, client, user_id)

    # Unlink every identity attached to the user.
    query_expr = ('identity.user_id={id}', {'id': user_id})
    yield gen.Task(Identity.VisitIndexKeys, client, query_expr, _VisitIdentity)

    # Add an analytics entry for this user.
    timestamp = Operation.GetCurrent().timestamp
    payload = 'terminate' if merged_with is None else 'merge=%s' % merged_with
    analytics = Analytics.Create(entity='us:%d' % user_id,
                                 type=Analytics.USER_TERMINATE,
                                 timestamp=timestamp,
                                 payload=payload)
    yield gen.Task(analytics.Update, client)

    # Terminate the user account.
    yield gen.Task(User.TerminateAccount, client, user_id, merged_with=merged_with)

    # Notify all friends that this user account has been terminated.
    yield NotificationManager.NotifyTerminateAccount(client, user_id)
Exemplo n.º 3
0
  def UpdateOperation(cls, client, callback, user_dict, settings_dict):
    """Invokes User.Update via operation execution."""
    yield gen.Task(User.UpdateWithSettings, client, user_dict, settings_dict)

    timestamp = Operation.GetCurrent().timestamp
    yield NotificationManager.NotifyUpdateUser(client, user_dict, settings_dict, timestamp)

    callback()
Exemplo n.º 4
0
    def UnlinkIdentityOperation(cls, client, user_id, identity):
        """Unlinks the specified identity from any associated viewfinder user."""
        # All contacts created during UnlinkIdentity are based on the current operation's timestamp.
        timestamp = Operation.GetCurrent().timestamp

        yield Identity.UnlinkIdentity(client, user_id, identity, timestamp)

        # Notify clients of any contacts that have been updated.
        yield NotificationManager.NotifyUnlinkIdentity(client, user_id,
                                                       identity, timestamp)
Exemplo n.º 5
0
    def _GetInstance(cls):
        """Ensures that a viewpoint lock tracker has been created and attached to the current
    operation.
    """
        op = Operation.GetCurrent()
        lock_tracker = op.context.get('viewpoint_lock_tracker')
        if lock_tracker is None:
            lock_tracker = ViewpointLockTracker()
            op.context['viewpoint_lock_tracker'] = lock_tracker

        return lock_tracker
Exemplo n.º 6
0
    def _InnerMethod(client, arg1, arg2):
      self._method_count += 1
      self.assertEqual(arg1, 1)
      self.assertEqual(arg2, 'hello')
      self.assertEqual(self._method_count, 2)

      # Assert that nested operation is derived from parent op.
      inner_op = Operation.GetCurrent()
      self.assertEqual(inner_op.user_id, outer_op.user_id)
      self.assertEqual(inner_op.timestamp, outer_op.timestamp)
      self.assertEqual(inner_op.operation_id, '+%s' % outer_op.operation_id)
Exemplo n.º 7
0
    def ApplyAccounting(cls, client, accounting, callback):
        """Apply an accounting object. This involves a query to fetch stats and applied op ids,
    check that this operation has not been applied, increment of values and Update.
    """
        op_id = Operation.GetCurrent().operation_id
        assert op_id is not None, 'accounting update outside an operation'

        def _OnException(accounting, type, value, traceback):
            # Entry was modified between Query and Update. Rerun the entire method.
            Accounting.ApplyAccounting(client, accounting, callback)

        def _OnQueryAccounting(entry):
            if entry is None:
                # No previous entry. Set op_id and set replace to false.
                # We can submit the accounting object directly since it has not been mutated.
                accounting.op_ids = op_id
                with util.Barrier(callback,
                                  on_exception=partial(_OnException,
                                                       accounting)) as b:
                    accounting.Update(client, b.Callback(), replace=False)
            else:
                prev_op_ids = entry.op_ids

                # Checks whether the op id has been applied and modifies op_ids accordingly.
                found = entry.IsOpDuplicate(op_id)
                if found:
                    # This operation has been applied: skip.
                    callback()
                    return

                entry.IncrementStatsFrom(accounting)

                # Entry exists: modify the object returned by Query and require that the op_ids
                # field has not changed since. If the existing entry was created by dbchk, it will
                # not have a op_ids field. Setting expected={'op_ids': None} is not equivalent to
                # expected={'op_ids': False}.
                with util.Barrier(callback,
                                  on_exception=partial(_OnException,
                                                       accounting)) as b:
                    entry.Update(client,
                                 b.Callback(),
                                 expected={'op_ids': prev_op_ids or False})

        Accounting.Query(client,
                         accounting.hash_key,
                         accounting.sort_key,
                         None,
                         _OnQueryAccounting,
                         must_exist=False)
Exemplo n.º 8
0
  def tearDown(self):
    # If validation is enabled, validate all viewpoint assets using the service API.
    # If the test failed, skip validation so we don't get extra redundant error reports
    # (The unittest framework reports errors in the main test and errors in tearDown separately)
    validate = self._validate and self._GetUnittestErrorCount() == self._unittest_error_count
    if validate:
      self._ValidateAssets()

    # Ensure that operations do not exist in the db.
    from viewfinder.backend.db.operation import Operation
    Operation.Scan(self._client, None, self.stop)
    ops, last_key = self.wait()
    if validate:
      self.assertTrue(len(ops) == 0, ops)
      self.assertTrue(last_key is None)

    # Cleanup all assets created during tests.
    self._tester.Cleanup(validate=validate, skip_validation_for=self._skip_validation_for)
    self._RunAsync(server_log.LogBatchPersistor.Instance().close)
    self._RunAsync(OpManager.Instance().Drain)

    shutil.rmtree(self._backup_dir)
    super(ServiceBaseTestCase, self).tearDown()
    self.assertIs(Operation.GetCurrent().operation_id, None)
Exemplo n.º 9
0
 def __init__(self, client):
     self._client = client
     self._op = Operation.GetCurrent()
Exemplo n.º 10
0
    def UpdateOperation(cls, client, act_dict, ph_dict):
        """Updates photo metadata."""
        assert ph_dict['user_id'] == Operation.GetCurrent().user_id

        # Call helper to carry out update of the photo.
        yield Photo.UpdatePhoto(client, act_dict=act_dict, **ph_dict)
Exemplo n.º 11
0
 def __init__(self, client, user, ep_dicts):
     super(HidePhotosOperation, self).__init__(client)
     self._op = Operation.GetCurrent()
     self._client = client
     self._user = user
     self._ep_dicts = ep_dicts
Exemplo n.º 12
0
 def __init__(self, client, user_id, viewpoint_id):
     super(RemoveViewpointOperation, self).__init__(client)
     self._op = Operation.GetCurrent()
     self._client = client
     self._user_id = user_id
     self._viewpoint_id = viewpoint_id
Exemplo n.º 13
0
 def _GetOperation(cls):
     """Gets the current operation, which must be in-scope."""
     operation = Operation.GetCurrent()
     assert operation.operation_id is not None, 'there must be current operation in order to create notification'
     return operation
Exemplo n.º 14
0
 def _OuterMethod(client):
   self._method_count += 1
   if self._method_count < 8:
     yield Operation.CreateNested(client, '_InnerMethod', {})
     self.assertEqual(Operation.GetCurrent().quarantine, 1)
Exemplo n.º 15
0
 def _InnererMethod(client, arg3):
   self.assertTrue(Operation.GetCurrent().operation_id.startswith('++'))
   self.assertEqual(arg3, 3)
   self._method_count += 1