desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Orchestrates the remove followers operation by executing each of the phases in turn.'
| @gen.coroutine
def _RemoveFollowers(self):
| lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._viewpoint_id))
try:
(yield self._Check())
self._client.CheckDBNotModified()
(yield self._Update())
(yield self._Account())
(yield Operation.TriggerFailpoint(self._client))
(yield self._Notify())
... |
'Gathers pre-mutation information:
1. Queries for existing followers and viewpoint.
2. Checkpoints list of followers that need to have REMOVED label added.
Validates the following:
1. Viewpoint exists and is not a default viewpoint.
2. Permission to modify viewpoint.
3. Permission to remove the requested followers.'
| @gen.coroutine
def _Check(self):
| (self._followers, _) = (yield gen.Task(Viewpoint.QueryFollowers, self._client, self._viewpoint_id, limit=Viewpoint.MAX_FOLLOWERS))
(self._viewpoint, self._removing_follower) = (yield gen.Task(Viewpoint.QueryWithFollower, self._client, self._user_id, self._viewpoint_id))
if (self._viewpoint is None):
... |
'Updates the database:
1. Removes (and/or makes unrevivable) specified followers to the viewpoint.'
| @gen.coroutine
def _Update(self):
| for follower in self._unrevivable_followers:
(yield follower.RemoveViewpoint(self._client, allow_revive=False))
|
'Makes accounting changes:
1. For removed followers.'
| @gen.coroutine
def _Account(self):
| acc_accum = AccountingAccumulator()
for follower_id in self._remove_id_set:
(yield acc_accum.RemoveViewpoint(self._client, follower_id, self._viewpoint_id))
(yield acc_accum.Apply(self._client))
|
'Creates notifications:
1. Notifies existing followers of the viewpoint that followers have been removed.
2. Notifies removed followers that they have been removed from the viewpoint.'
| @gen.coroutine
def _Notify(self):
| (yield NotificationManager.NotifyRemoveFollowers(self._client, self._viewpoint_id, self._followers, self._remove_ids, self._act_dict))
|
'Entry point called by the operation framework.'
| @classmethod
@gen.coroutine
def Execute(cls, client, user_id, webapp_dev_id, identity_key, reason=None):
| (yield CreateProspectiveOperation(client, user_id, webapp_dev_id, identity_key, reason=reason)._CreateProspective())
|
'Create the prospective user and identity.'
| @gen.coroutine
def _CreateProspective(self):
| (self._new_user, _) = (yield User.CreateProspective(self._client, self._new_user_id, self._webapp_dev_id, self._identity_key, self._op.timestamp))
if (system_users.NARRATOR_USER is not None):
if (self._op.checkpoint is None):
self._unique_id_start = (yield gen.Task(User.AllocateAssetIds, sel... |
'Creates the welcome conversation at the db level. Operations are not used in order
to avoid creating notifications, sending alerts, taking locks, running nested operations,
etc.'
| @gen.coroutine
def _CreateWelcomeConversation(self):
| from viewfinder.backend.www.system_users import NARRATOR_USER
from viewfinder.backend.www.system_users import NARRATOR_UPLOAD_PHOTOS, NARRATOR_UPLOAD_PHOTOS_2, NARRATOR_UPLOAD_PHOTOS_3
self._acc_accum = AccountingAccumulator()
self._unique_id = self._unique_id_start
self._update_seq = 1
self._vi... |
'Creates an activity by invoking "activity_func" with the given args.'
| @gen.coroutine
def _CreateActivity(self, sharer_user, timestamp, activity_func, **kwargs):
| activity_id = Activity.ConstructActivityId(timestamp, self._new_user.webapp_dev_id, self._unique_id)
self._unique_id += 1
activity = (yield activity_func(self._client, sharer_user.user_id, self._viewpoint_id, activity_id, timestamp, update_seq=self._update_seq, **kwargs))
self._update_seq += 1
raise... |
'Creates a new episode containing the given photos.'
| @gen.coroutine
def _CreateEpisodeWithPosts(self, sharer_user, parent_ep_id, ph_dicts):
| episode_id = Episode.ConstructEpisodeId(self._op.timestamp, self._new_user.webapp_dev_id, self._unique_id)
self._unique_id += 1
episode = (yield gen.Task(Episode.CreateNew, self._client, episode_id=episode_id, parent_ep_id=parent_ep_id, user_id=sharer_user.user_id, viewpoint_id=self._viewpoint_id, publish_t... |
'Creates a new comment and a corresponding activity.'
| @gen.coroutine
def _PostComment(self, sharer_user, timestamp, message, asset_id=None):
| comment_id = Comment.ConstructCommentId(timestamp, self._new_user.webapp_dev_id, self._unique_id)
self._unique_id += 1
comment = (yield Comment.CreateNew(self._client, viewpoint_id=self._viewpoint_id, comment_id=comment_id, user_id=sharer_user.user_id, asset_id=asset_id, timestamp=timestamp, message=message... |
'Entry point called by the operation framework.'
| @classmethod
@gen.coroutine
def Execute(cls, client, activity, user_id, viewpoint, episodes, contacts):
| (yield ShareNewOperation(client, activity, user_id, viewpoint, episodes, contacts)._ShareNew())
|
'Orchestrates the share new operation by executing each of the phases in turn.'
| @gen.coroutine
def _ShareNew(self):
| lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._viewpoint_id))
try:
if (not (yield self._Check())):
return
self._client.CheckDBNotModified()
(yield self._Update())
(yield self._Account())
(yield Operation.TriggerFailpoint(self._client))
... |
'Gathers pre-mutation information:
1. Checkpoints list of contacts that need to be made prospective users.
2. Cover photo, if not specified.
Validates the following:
1. Max follower limit.
2. Permissions to share from source episodes.
3. Permission to create new viewpoint.
4. Cover photo is contained in the request.
Re... | @gen.coroutine
def _Check(self):
| if ((len(self._contact_dicts) + 1) > Viewpoint.MAX_FOLLOWERS):
raise LimitExceededError(('User %d attempted to exceed follower limit on viewpoint "%s" by creating a viewpoint with %d followers.' % (self._user_id, self._viewpoint_id, (len(self._contact_dicts) +... |
'Updates the database:
1. Creates prospective users.
2. Creates new viewpoint, episodes, and posts.'
| @gen.coroutine
def _Update(self):
| (yield self._ResolveContacts(self._contact_dicts, self._contact_ids, reason=('share_new=%d' % self._user_id)))
follower_ids = list(set((user_id for user_id in self._contact_user_ids if (user_id != self._user_id))))
(self._viewpoint, self._followers) = (yield gen.Task(Viewpoint.CreateNewWithFollowers, self._... |
'Makes accounting changes:
1. For revived followers.
2. For new followers.'
| @gen.coroutine
def _Account(self):
| photo_ids = [photo_id for new_ep_dict in self._new_ep_dicts for photo_id in new_ep_dict['photo_ids']]
acc_accum = AccountingAccumulator()
(yield acc_accum.SharePhotos(self._client, self._user_id, self._viewpoint_id, photo_ids, [follower.user_id for follower in self._followers]))
(yield acc_accum.Apply(s... |
'Creates notifications:
1. Notifies removed followers that conversation has new activity.
2. Notifies users with contacts that have become prospective users.
3. Notifies existing followers of the viewpoint that new followers have been added.
4. Notifies new followers that they have been added to a viewpoint.'
| @gen.coroutine
def _Notify(self):
| identity_keys = [contact_dict['identity'] for (contact_dict, (user_exists, user_id, webapp_dev_id)) in zip(self._contact_dicts, self._contact_ids) if (not user_exists)]
(yield NotificationManager.NotifyCreateProspective(self._client, identity_keys, self._op.timestamp))
(yield NotificationManager.NotifyShare... |
'Asynchronously puts the specified key/value pair, overwriting any
existing stored data. The value must be a byte string (str) instance.
If "content_type" is defined, then it defines the MIME type and
charset of the content bytes. If the operation succeeds, then the
callback will be invoked with no arguments.
If reques... | def Put(self, key, value, callback, content_type=None, request_timeout=None):
| raise NotImplementedError('must implement in subclass')
|
'Asynchronously retrieves the specified key/value pair. If the
operation succeeds, then the callback will be invoked with a single
byte string (str) argument containing the value.
If must_exist is False and the file is not found, the callback will be
invoked with None.'
| def Get(self, key, callback, must_exist=True):
| raise NotImplementedError('must implement in subclass')
|
'Asynchronously retrieves all keys in the bucket in alphanumeric
order, up to a limit of "maxkeys" if specified or the AWS-defined
limit of 1000. If "prefix" is specified, only keys which match
the prefix are returned. If "marker" is specified, the list will
begin with the first key that alphanumerically follows the ... | def ListKeys(self, callback, prefix=None, marker=None, maxkeys=None):
| raise NotImplementedError('must implement in subclass')
|
'Asynchronously retrieve common prefixes.
A common prefix is a string found between "prefix" (if any) and the delimiter character.
The returned prefixes include "prefix" and the delimiter. Delimiter cannot be None.
Each "common prefix" will count as one against max_keys.
The return value is (prefixes, keys) where keys ... | def ListCommonPrefixes(self, delimiter, callback, prefix=None, marker=None, maxkeys=None):
| raise NotImplementedError('must implement in subclass')
|
'Asynchronously deletes the specified key. If the operation succeeds,
then the callback is invoked with no arguments.'
| def Delete(self, key, callback):
| raise NotImplementedError('must implement in subclass')
|
'Generates a URL that can be used retrieve the specified key. If \'cache_control\' is
given, it will result in a Cache-Control header being added to any S3 responses. The
expires_in parameter specifies how long (in seconds) the URL is valid for.
content-type forces the content-type of the downloaded file. eg: use text/... | def GenerateUrl(self, key, method='GET', cache_control=None, expires_in=constants.SECONDS_PER_DAY, content_type=None):
| raise NotImplementedError('must implement in subclass')
|
'Generates a URL for a PUT request to allow a client to store
the specified key directly.'
| def GenerateUploadUrl(self, key, content_type=None, content_md5=None, expires_in=constants.SECONDS_PER_DAY, max_bytes=(5 << 20)):
| raise NotImplementedError('must implement in subclass')
|
'Sets a new instance for testing.'
| @staticmethod
def SetInstance(name, instance):
| setattr(ObjectStore, ObjectStore._InstanceName(name), instance)
|
'Returns true if instance \'name\' exists.'
| @staticmethod
def HasInstance(name):
| return hasattr(ObjectStore, ObjectStore._InstanceName(name))
|
'Return the list of instances.'
| @staticmethod
def ListInstances():
| ret = []
for attr_name in ObjectStore.__dict__.keys():
parsed = re.match('_([-a-z0-9]+)_instance$', attr_name)
if (not parsed):
continue
ret.append(parsed.groups()[0])
return ret
|
'Asynchronously puts the specified S3 key/value pair, overwriting any
existing stored data. The value must be a byte string (str) instance.
The raw str bytes are stored in S3. If "content_type" is defined, then
the Content-Type header is set to its value. If the operation succeeds,
then the callback will be invoked wit... | def Put(self, key, value, callback, content_type=None, request_timeout=20.0):
| assert (not self._read_only), 'Received "Put" request on read-only object store.'
def _OnCompletedPut(start_time, response):
if response.error:
raise response.error
_secs_per_put.add((time.time() - start_time))
callback()
start_time = time.time()
_pu... |
'Asynchronously retrieves the specified key/value pair. If the
operation succeeds, then the callback will be invoked with a single
byte string (str) argument containing the value.
If must_exist is False and the file is not found, the callback will be
invoked with None.'
| def Get(self, key, callback, must_exist=True):
| def _OnCompletedGet(response):
if response.error:
if (must_exist or (response.error.code != 404)):
raise response.error
else:
callback(None)
else:
callback(response.body)
_gets_per_min.increment()
self._async_s3_conn.make_re... |
'List files in a S3 bucket.'
| def ListKeys(self, callback, prefix=None, marker=None, maxkeys=None):
| def _OnCompletedGet(response):
if response.error:
raise response.error
ns = '{http://s3.amazonaws.com/doc/2006-03-01/}'
item_element = ('%sContents' % ns)
key_element = ('%sKey' % ns)
bucket_list = ElementTree.XML(response.body)
result = [item.find(key_ele... |
'List files in a S3 bucket and return metadata fields.
Generates a dictionary of {\'file0\': {\'field0\':\'fieldvalue\', ...}, ... \'fileN\': {\'field0\':\'fieldvalue\'}}.'
| def ListKeyMetadata(self, callback, prefix=None, marker=None, maxkeys=None, fields=None):
| def _OnCompletedGet(response):
if response.error:
raise response.error
ns = '{http://s3.amazonaws.com/doc/2006-03-01/}'
item_element = ('%sContents' % ns)
key_element = ('%sKey' % ns)
wanted = {}
for f in fields:
wanted[('%s%s' % (ns, f))] = f
... |
'List files in a S3 bucket.'
| def ListCommonPrefixes(self, delimiter, callback, prefix=None, marker=None, maxkeys=None):
| assert (delimiter is not None), 'delimiter arg is required on ListCommonPrefixes'
def _OnCompletedGet(response):
if response.error:
raise response.error
ns = '{http://s3.amazonaws.com/doc/2006-03-01/}'
common_prefix_element = ('%sCommonPrefixes' % ns)
p... |
'Asynchronously deletes the specified key. If the operation succeeds,
then the callback is invoked with no arguments.'
| def Delete(self, key, callback):
| assert (not self._read_only), 'Received "Delete" request on read-only object store.'
def _OnCompletedDelete(response):
if response.error:
raise response.error
callback()
self._async_s3_conn.make_request('DELETE', bucket=self._bucket_name, key=key, callback=_OnCo... |
'Generates a URL that can be used retrieve the specified key. If \'cache_control\' is
given, it will result in a Cache-Control header being added to any S3 responses. The
expires_in parameter specifies how long (in seconds) the URL is valid for.
content-type forces the content-type of the downloaded file. eg: use text/... | def GenerateUrl(self, key, method='GET', cache_control=None, expires_in=constants.SECONDS_PER_DAY, content_type=None):
| response_headers = {}
util.SetIfNotNone(response_headers, 'response-cache-control', cache_control)
util.SetIfNotNone(response_headers, 'response-content-type', content_type)
return self._s3_conn.generate_url(expires_in, method, self._bucket_name, key, response_headers=(response_headers or None))
|
'Generates a URL for a PUT request to allow a client to store the specified key directly
to S3 from a browser or mobile client. \'max_bytes\' limits the upload file size to prevent
D.O.S. attacks.
TODO(andy) max_bytes is not currently enforced, need to fix this.'
| def GenerateUploadUrl(self, key, content_type=None, content_md5=None, expires_in=constants.SECONDS_PER_DAY, max_bytes=(5 << 20)):
| headers = {}
util.SetIfNotNone(headers, 'Content-Type', content_type)
util.SetIfNotNone(headers, 'Content-MD5', content_md5)
return self._s3_conn.generate_url(expires_in, 'PUT', self._bucket_name, key, headers=(headers or None))
|
'Add a handler to the list of handlers registered with this persistor.'
| def AddHandler(self, handler):
| if (not (handler in self._handlers)):
self._handlers.append(handler)
|
'Remove a handler from the list of handlers registered with this persistor.'
| def RemoveHandler(self, handler):
| if (handler in self._handlers):
self._handlers.remove(handler)
|
'Basic test for a log persistor.'
| def testPersistor(self):
| backup_dir = tempfile.mkdtemp()
persistor = LogBatchPersistor(backup_dir=backup_dir)
batches = [LogBatch('Log batch buffer 1A', ObjectStore.SERVER_LOG, 'test1', 'keyA'), LogBatch('Log batch buffer 2B', ObjectStore.SERVER_LOG, 'test2', 'keyB'), LogBatch('Log batch buffer 3C', Objec... |
'Tests backup storage in case the object store is down. Also verifies close() method.'
| def testBadObjStore(self):
| backup_dir = tempfile.mkdtemp()
persistor = LogBatchPersistor(backup_dir=backup_dir)
batches = [LogBatch('Log batch buffer 1A', ObjectStore.SERVER_LOG, 'test1', 'keyA'), LogBatch('Log batch buffer 2B', ObjectStore.SERVER_LOG, 'test2', 'keyB'), LogBatch('Log batch buffer 3C', Objec... |
'Verifies the persistor will reattempt failed object store writes after a timeout'
| def testRestoreTimeout(self):
| backup_dir = tempfile.mkdtemp()
persistor = LogBatchPersistor(backup_dir=backup_dir)
batches = [LogBatch('Log batch buffer 1A', ObjectStore.SERVER_LOG, 'test1', 'keyA'), LogBatch('Log batch buffer 2B', ObjectStore.SERVER_LOG, 'test2', 'keyB'), LogBatch('Log batch buffer 3C', Objec... |
'Tests that the server log writes to object store.'
| def testBatching(self):
| basic_log = _BasicLogHandler(max_buffer_bytes=100)
record = logging.makeLogRecord({'level': logging.INFO, 'msg': 'test'})
basic_log.emit(record)
basic_log.flush()
self._RunAsync(self._VerifyLog, ['test'])
|
'Tests log messages with both 8-bit byte strings and unicode.'
| def testBadLogMessages(self):
| basic_log = _BasicLogHandler(max_buffer_bytes=100)
record = logging.makeLogRecord({'level': logging.INFO, 'msg': '\x80abc'})
basic_log.emit(record)
record = logging.makeLogRecord({'level': logging.INFO, 'msg': u'\x80abc'})
basic_log.emit(record)
basic_log.flush()
|
'Tests multiple flushes.'
| def testMultipleFlushes(self):
| basic_log = _BasicLogHandler(flush_interval_secs=0.1)
for i in xrange(8):
record = logging.makeLogRecord({'level': logging.INFO, 'msg': ('test%d' % i)})
basic_log.emit(record)
basic_log.flush()
self._RunAsync(self._VerifyLog, [('test%d' % i) for i in range(8)])
|
'Tests that the server log flushes based on maximum bytes written.'
| def testMaxBytesFlush(self):
| basic_log = _BasicLogHandler(max_buffer_bytes=100)
msg = ('test' * 100)
record = logging.makeLogRecord({'level': logging.INFO, 'msg': msg})
basic_log.emit(record)
self._RunAsync(self._VerifyLog, [msg])
|
'Tests that the server log flushes after maximum flush interval.'
| def testTimeoutFlush(self):
| basic_log = _BasicLogHandler(flush_interval_secs=0.1)
record = logging.makeLogRecord({'level': logging.INFO, 'msg': 'test'})
basic_log.emit(record)
self._RunAsync(self.io_loop.add_timeout, (time.time() + 0.15))
self._RunAsync(self._VerifyLog, ['test'])
|
'Verify that \'close()\' is called on the server handler when the persistor
is closed.'
| def testFinishServerLog(self):
| persistor = _FakePersistor()
InitServerLog(persistor)
self.assertEqual(2, len(persistor._handlers))
basic_handler = _BasicLogHandler()
basic_handler.setLevel(logging.INFO)
with basic_handler.LoggingContext():
self.assertEqual(3, len(persistor._handlers))
self.assertEqual(0, len(p... |
'Verify that the error log handler properly batches.'
| def testFinishServerLogWithErrors(self):
| persistor = _FakePersistor()
InitServerLog(persistor)
self.assertEqual(2, len(persistor._handlers))
basic_handler = _BasicLogHandler()
basic_handler.setLevel(logging.INFO)
with basic_handler.LoggingContext():
self.assertEqual(3, len(persistor._handlers))
self.assertEqual(0, len(p... |
'Verifies that there are len(\'exp_msg\') batches stored
and that each contains the expected message as contents.'
| def _VerifyLog(self, exp_msgs, callback):
| def _DoVerify():
batches = self._persistor.batches
self.assertEqual(len(batches), len(exp_msgs))
for (key, msg) in zip(sorted(batches.keys()), exp_msgs):
value = batches[key].buffer
regexp = re.compile(('\\[pid:[0-9]+\\] .*:[0-9]+: %s' % msg))
self.a... |
'Verify that error-counting performance counters are working correctly.
These performance counters are implemented as a log filter.'
| def testErrorCounters(self):
| meter = counters.Meter(counters.counters.viewfinder.errors)
InitServerLog(_FakePersistor())
def _CheckCounters(expected_errors, expected_warnings):
sample = meter.sample()
self.assertEqual(expected_errors, sample.viewfinder.errors.error)
self.assertEqual(expected_warnings, sample.vie... |
'Try several successful AsyncS3Connection.make_request operations using a byte string value.'
| def testMakeByteRequest(self):
| self._TestMakeRequest('abc 123\n\x00\xc3\xb1')
|
'Try calling AsyncS3Connection.make_request with a Unicode string (not supported).'
| def testMakeUnicodeRequest(self):
| self.assertRaises(AssertionError, self._TestMakeRequest, u'abc 123\n\x00\u1000')
|
'Trigger errors in AsyncS3Connection.make_request using the Simple HTTP async client.'
| def testMakeRequestError(self):
| saved = self._SaveHTTPClientConfig()
try:
httpclient.AsyncHTTPClient.configure(None)
self.assertIsInstance(httpclient.AsyncHTTPClient(io_loop=self.io_loop), simple_httpclient.SimpleAsyncHTTPClient)
self._TestMakeRequestError()
finally:
self._RestoreHTTPClientConfig(saved)
|
'Trigger errors in AsyncS3Connection.make_request using the Curl HTTP async client.'
| @unittest.skipIf((pycurl is None), 'pycurl not available')
def testMakeRequestCurlError(self):
| from tornado import curl_httpclient
saved = self._SaveHTTPClientConfig()
try:
httpclient.AsyncHTTPClient.configure('tornado.curl_httpclient.CurlAsyncHTTPClient')
self.assertIsInstance(httpclient.AsyncHTTPClient(io_loop=self.io_loop), curl_httpclient.CurlAsyncHTTPClient)
self._TestMak... |
'Test Get must_exist parameter.'
| def testGetMustExist(self):
| unknown_key = 'some/unknown/key'
self.assertRaises(IOError, self._RunAsync, self.object_store.Get, unknown_key)
self.assertRaises(IOError, self._RunAsync, self.object_store.Get, unknown_key, must_exist=True)
self.assertIsNone(self._RunAsync(self.object_store.Get, unknown_key, must_exist=False))
self... |
'Test asynchronous S3 object store Put and Get methods.'
| def testPutGet(self):
| baseline = self._GetCounters()
self._RunAsync(self.object_store.Put, self.key, 'world')
s = self._RunAsync(self.object_store.Get, self.key)
self.assertEquals(s, 'world')
self._CheckCounters(baseline, 1, 1)
|
'Test Get must_exist parameter.'
| def testGetMustExist(self):
| unknown_key = 'some/unknown/key'
self.assertRaises(httpclient.HTTPError, self._RunAsync, self.object_store.Get, unknown_key)
self.assertRaises(httpclient.HTTPError, self._RunAsync, self.object_store.Get, unknown_key, must_exist=True)
self.assertIsNone(self._RunAsync(self.object_store.Get, unknown_key, m... |
'Test GenerateUrl method on S3 object store.'
| def testGenerateUrl(self):
| self._RunAsync(self.object_store.Put, self.key, 'foo')
url = self.object_store.GenerateUrl(self.key, cache_control='private,max-age=31536000', expires_in=100)
response = httpclient.HTTPClient().fetch(url, method='GET')
self.assertEqual(response.body, 'foo')
self.assertEqual(response.headers['Cache-C... |
'Test GenerateUrl method with \'HEAD\' method on S3 object store.'
| def testGenerateHeadUrl(self):
| self._RunAsync(self.object_store.Put, self.key, 'foo')
url = self.object_store.GenerateUrl(self.key, method='HEAD', expires_in=100)
response = httpclient.HTTPClient().fetch(url, method='HEAD', request_timeout=3.0)
self.assertEqual(response.code, 200)
self.assertEqual(response.headers['Content-Length... |
'Test GenerateUploadUrl method on S3 object store.'
| def testGenerateUploadUrl(self):
| content = 'hello world'
hasher = hashlib.md5()
hasher.update(content)
md5 = base64.b64encode(hasher.digest())
upload_url = self.object_store.GenerateUploadUrl(self.key, content_type='text/plain', content_md5=md5, expires_in=100, max_bytes=1024)
headers = {'Content-Type': 'text/plain', 'Conten... |
'Test S3 ETAG mechanism.'
| def testEtag(self):
| hasher = hashlib.md5()
content = 'hello world'
hasher.update(content)
digest = ('"%s"' % hasher.hexdigest())
upload_url = self.object_store.GenerateUploadUrl(self.key, expires_in=100, max_bytes=1024)
response = httpclient.HTTPClient().fetch(upload_url, method='PUT', body=content)
self.ass... |
'Create a new batch for the given buffer which will be saved in the object
store with the given name. They key within the object store will be synthesized
using any additional positional arguments.'
| def __init__(self, buffer, store_name, *keyparts):
| self.buffer = buffer
self.store_name = store_name
assert (len(keyparts) > 0), 'Must provide at least one parameter to create a batch key.'
keyparts = [str(part) for part in keyparts]
for part in keyparts:
assert ('_' not in keyparts)
assert ('/' not in k... |
'Synthesize a string key for this batch which will be used to identify this batch
in the object store.'
| def Key(self):
| return '/'.join(self.keyparts)
|
'Synthesize a string key for this batch which will be used to identify this batch
in a local file system, which may have different character requirements.'
| def FileSystemKey(self):
| return '_'.join(self.keyparts)
|
'Decode the key from a previously created log batch.'
| @classmethod
def DecodeKey(cls, key):
| return key.split('/')
|
'Decode the file system key from a previously created log batch.'
| @classmethod
def DecodeFileSystemKey(cls, key):
| return key.split('_')
|
'Initialize a new BatchingLogHandler. max_buffer_bytes determines the maximum size of each batch,
while flush_interval_secs determines the maximum amount of time that a batch can be active before
persisting it.
\'persistor\' should be a LogBatchPersistor - each completed batch from this handler will be sent to this
pe... | def __init__(self, max_buffer_bytes=None, flush_interval_secs=None, persistor=None):
| super(BatchingLogHandler, self).__init__()
self._max_buffer_bytes = (max_buffer_bytes or options.options.server_log_max_buffer_bytes)
self._flush_interval_secs = (flush_interval_secs or options.options.server_log_flush_interval_secs)
self._persistor = (persistor or LogBatchPersistor.Instance())
self... |
'Flush this handler by saving the current buffer as a complete batch and
beginning a new batch.'
| def flush(self):
| if self._closing:
return
with _DisableLoggingContext(self):
if (self._flush_timeout and (IOLoop.current() is not None)):
IOLoop.current().remove_timeout(self._flush_timeout)
self._flush_timeout = None
self._CutBatch()
|
'Emits the specified record by writing it to the in-memory log
handler. If the size of the in-memory handler\'s buffer exceeds
_max_buffer_bytes, flushes it to the object store.'
| def emit(self, record):
| if self._closing:
return
if (self._buffer is None):
self._NewBatch()
self._inner_handler.emit(record)
if (self._buffer.tell() >= self._max_buffer_bytes):
self.flush()
elif (not self._flush_timeout):
deadline = (self._start_timestamp + self._flush_interval_secs)
... |
'Returns a ContextManager that adds this handler to the given logger when
entered, removing it upon exit. If no logger is given, the default logger
from logging.getLogger will be used.'
| @contextmanager
def LoggingContext(self, logger=None):
| try:
logger = (logger or logging.getLogger())
logger.addHandler(self)
(yield)
finally:
logger.removeHandler(self)
|
'Returns a tornado StackContext which adds this handler to the given logger when
entered, removing it upon exit. If no logger is given, the default logger
from logging.getLogger will be used.'
| def LoggingStackContext(self, logger=None):
| return stack_context.StackContext(partial(self.LoggingContext, logger))
|
'Close this handler, persisting any outstanding logs as a new batch. The batch can
be suppressed by passing save_batch=False to this method.'
| def close(self, save_batch=True):
| super(BatchingLogHandler, self).close()
self._closing = True
with _DisableLoggingContext(self):
if save_batch:
self._CutBatch()
self._Unregister()
|
'Method which wraps a buffer into a log batch in order to persist it. This
method is intended to be overridden in derived classes in order to properly
generate the keys for different log types.'
| def MakeBatch(self, buffer):
| raise NotImplementedError('Must implement MakeBatch in a subclass.')
|
'Generates a logging batch from the current log buffer and sends it to the persistor
in order to be saved.'
| def _CutBatch(self):
| if (self._buffer is not None):
batch = None
try:
log_buf = self._buffer.getvalue()
if (type(log_buf) is unicode):
import tornado.escape
log_buf = tornado.escape.utf8(log_buf)
batch = self.MakeBatch(log_buf)
except:
... |
'Begins a new log batch.'
| def _NewBatch(self):
| self._buffer = StringIO()
self._inner_handler = logging.StreamHandler(self._buffer)
self._inner_handler.setLevel(logging.INFO)
self._inner_handler.setFormatter(logging_utils.FORMATTER)
self._start_timestamp = time.time()
|
'Registers this handler with its persistor.'
| def _Register(self):
| self._persistor.AddHandler(self)
|
'Unregisters this handler from its persistor.'
| def _Unregister(self):
| self._persistor.RemoveHandler(self)
|
'Constructs a server log batch for the given buffer. Batches are destined
for the server log object store, with a key derived from a current timestamp
and process information.'
| def MakeBatch(self, buffer):
| try:
from viewfinder.backend.base import main
instance_id = ami_metadata.GetAMIMetadata()['meta-data/instance-id']
except (KeyError, TypeError):
instance_id = socket.gethostname()
return LogBatch(buffer, ObjectStore.SERVER_LOG, self._jobname, self.SERVER_LOG_CATEGORY, self._Formatted... |
'Checks the level of record. Records of level WARNING or above will be noted in performance
counters, which are used for monitoring purposes.'
| def emit(self, record):
| super(ErrorLogHandler, self).emit(record)
if self._closing:
return
if (record.levelno >= logging.ERROR):
_error_count.increment()
elif (record.levelno >= logging.WARNING):
_warning_count.increment()
|
'\'backup_dir\' is augmented using the process name (as taken from sys.argv[0]).'
| def __init__(self, backup_dir=None):
| self._proc_name = os.path.basename(sys.argv[0])
self._backup_dir = os.path.join((backup_dir or os.path.expanduser(options.options.server_log_backup_dir)), self._proc_name)
self._in_flight = {}
self._handlers = []
self._wait_callbacks = deque()
self._restore_timeout = None
self._closing = Fal... |
'Relibably persists the given LogBatch to object storage. If the batch cannot immediately
be uploaded to object storage, it is instead persisted to the local filesystem and will be
uploaded to storage at a later time.'
| def PersistLogBatch(self, batch):
| self._PersistToObjStore(batch)
|
'Add a handler to the list of handlers registered with this persistor.'
| def AddHandler(self, handler):
| if (not (handler in self._handlers)):
self._handlers.append(handler)
|
'Remove a handler from the list of handlers registered with this persistor.'
| def RemoveHandler(self, handler):
| if (handler in self._handlers):
self._handlers.remove(handler)
|
'Closes this LogBatchPersistor. Any extant, in-flight puts to the object store are persisted
to the backup directory immediately.'
| def close(self, callback=None):
| timeout = None
callback = stack_context.wrap(callback)
self._closing = True
def _OnFlush():
if (timeout is not None):
IOLoop.current().remove_timeout(timeout)
if self._in_flight:
logging.warning('unflushed server log buffers; writing to backup ... |
'Registers a callback to be invoked when all currently in-flight logs have been
successfully persisted to either the object store or local storage. Intended
only for use in testing.'
| def Wait(self, callback):
| if self._in_flight:
callback = stack_context.wrap(callback)
self._wait_callbacks.append(callback)
else:
callback()
|
'Writes the given log batch to the object store. The \'restore\'
parameter indicates that this is an attempt to restore the log, in
which case we do not rewrite it to backup on a subsequent failure.
If there are callbacks waiting on a pending flush and there are no
more inflight log buffers, returns all callbacks.'
| def _PersistToObjStore(self, batch, restore=False):
| batch_key = batch.Key()
def _ProcessWaitCallbacks():
del self._in_flight[batch_key]
if (not self._in_flight):
while self._wait_callbacks:
self._wait_callbacks.popleft()()
def _OnPut():
logging.info(('Successfully persisted log batch %s to ... |
'Writes a batch to the local filesystem.'
| def _PersistToBackup(self, batch):
| filename = self._BackupFileName(batch)
assert (not os.path.isfile(filename))
try:
os.makedirs(os.path.dirname(filename))
except:
pass
with open(filename, 'w') as f:
f.write(batch.buffer)
logging.info(('Persisted log batch %s/%s to local backup directo... |
'Restores all server logs which are currently persisted to the
backup directory. Each is sent in turn to the object store.'
| def _RestoreBackups(self):
| if self._restore_timeout:
IOLoop.current().remove_timeout(self._restore_timeout)
self._restore_timeout = None
if (not os.path.isdir(self._backup_dir)):
os.makedirs(self._backup_dir)
try:
assert os.path.isdir(self._backup_dir), self._backup_dir
store_names = os.listdir... |
'Sets the restore timeout if it is not already set. The timeout will trigger
an attempt to upload local batch backups to the server.'
| def _SetRestoreTimeout(self, timeout_secs=None):
| if (timeout_secs is None):
timeout_secs = self._RESTORE_INTERVAL_SECS
if (not self._restore_timeout):
if (timeout_secs > 0):
logging.info(('setting a timeout of %fs to reattempt object store persistance' % self._RESTORE_INTERVAL_SECS))
deadline ... |
'Sets a new instance for testing.'
| @staticmethod
def SetInstance(persistor):
| LogBatchPersistor._instance = persistor
|
'Retry on:
1. HTTP error codes 500 (Internal Server Error) and 503 (Service
Unavailable).
2. Tornado HTTP error code 599, which typically indicates some kind
of general network failure of some kind.
3. Socket-related errors.'
| def _ShouldRetry(self, response):
| if response.error:
if ((type(response.error) == socket.error) or (type(response.error) == socket.gaierror)):
return True
if isinstance(response.error, HTTPError):
code = response.error.code
if (code in (500, 503, 599)):
return True
return False... |
'Start an asynchronous HTTP operation against the S3 service. When
the operation is complete, the \'callback\' function will be invoked,
with the HTTP response object as its only parameter. If a failure
occurs during execution of the operation, it may be retried, according
to the retry policy with which this instance w... | def make_request(self, method, bucket='', key='', headers=None, params=None, body=None, request_timeout=20.0, callback=None):
| CallWithRetryAsync(self.retry_policy, self._make_request, method, bucket, key, headers, params, body, request_timeout, callback=callback)
|
'Wrapped by CallWithRetryAsync in order to support retry.'
| def _make_request(self, method, bucket, key, headers, params, body, request_timeout, callback):
| path = AsyncS3Connection.DefaultCallingFormat.build_path_base(bucket, key)
auth_path = AsyncS3Connection.DefaultCallingFormat.build_auth_path(bucket, key)
host = AsyncS3Connection.DefaultCallingFormat.build_host(self.server_name(), bucket)
assert ((not body) or (type(body) is str)), ('Only support ... |
'Called by AWSAuthConnection.__init__ in order to determine which
auth handler to construct. In this case, S3 HMAC signing should be used.'
| def _required_auth_capability(self):
| return ['s3']
|
'Override tornado\'s xsrf cookie check.
S3 doesn\'t require XSRF, so we won\'t expect it for the file object store in the local server.'
| def check_xsrf_cookie(self):
| pass
|
'Start this scenario. It will run at the configured frequency until StopLoop() is called.'
| def StartLoop(self, device):
| logger = logging.LoggerAdapter(logging.getLogger(), {'scenario': self.name})
def _OnComplete():
self._timeout = IOLoop.current().add_timeout((time.time() + self.frequency), _RunIteration)
def _OnException(typ, val, tb):
if ((typ, val, tb) != (None, None, None)):
if (typ is web.HT... |
'Stop the loop if it is already running.'
| def StopLoop(self):
| if (self._timeout is not None):
IOLoop.current().remove_timeout(self._timeout)
|
'Send an arbitrary service request to the viewfinder service from this client.
The request is a json request consisting of any additional keyword arguments to
SendRequest.'
| def SendRequest(self, service_path, callback, method='POST', **kwargs):
| if (self._user_cookie is None):
raise ScenarioLoginError(('Client %s can not be used until it is has a valid authorization cookie.' % self.name))
http_client = httpclient.AsyncHTTPClient()
url = self._GetUrl(service_path)
headers = {'Cookie': ('user=%s;_xsr... |
'Return true if this device has a valid authentication cookie from the server.'
| def IsAuthenticated(self):
| return (self._user_cookie is not None)
|
'Retrieve a user code from google\'s device login API. The given callback will
be invoked with the user code and a URL where the user code can be used to
authenticate a google account.'
| def GetUserCode(self, callback):
| def _OnGetDeviceCode(response):
response_dict = www_util.ParseJSONResponse(response)
self._device_code = response_dict.get('device_code')
callback(response_dict.get('user_code'), response_dict.get('verification_url'))
request_args = {'client_id': secrets.GetSecret('google_client_mobile_i... |
'Poll the google authorization service to find if the user code generated
in a previous call to GetUserCode() has been used to authorize a google user account.
If an account has been authorized, this method will use that authorization to log
into the viewfinder service, thus retrieving the needed authentication cookie.... | def PollForAuthentication(self, callback):
| if (not hasattr(self, '_device_code')):
raise ScenarioLoginError('Must call GetUserCode() on a device before using the PollForAuthentication() method.')
http_client = httpclient.AsyncHTTPClient()
def _OnLogin(response):
if (not (response.code in (200, 302))):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.