desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Prints a nag message and updates the nag file\'s timestamp.
Because we don\'t want to nag the user everytime, we store a simple
yaml document in the user\'s home directory. If the timestamp in this
doc is over a week old, we\'ll nag the user. And when we nag the user,
we update the timestamp in this doc.
Args:
msg: ... | def _Nag(self, msg, latest, version, force=False):
| nag = self._ParseNagFile()
if (nag and (not force)):
last_nag = datetime.datetime.fromtimestamp(nag.timestamp)
if ((datetime.datetime.now() - last_nag) < datetime.timedelta(weeks=1)):
logging.debug('Skipping nag message')
return
if (nag is None):
nag = N... |
'Determines if the user wants to check for updates.
On startup, the dev_appserver wants to check for updates to the SDK.
Because this action reports usage to Google when the user is not
otherwise communicating with Google (e.g. pushing a new app version),
the user must opt in.
If the user does not have a nag file, we w... | def AllowedToCheckForUpdates(self, input_fn=raw_input):
| nag = self._ParseNagFile()
if (nag is None):
nag = NagFile()
nag.timestamp = 0.0
if (nag.opt_in is None):
answer = input_fn('Allow dev_appserver to check for updates on startup? (Y/n): ')
answer = answer.strip().lower()
if ((answer == 'n') o... |
'Initialize a WorkerThread instance.
Args:
thread_pool: An AdaptiveThreadPool instance.
thread_gate: A ThreadGate instance.
name: A name for this WorkerThread.'
| def __init__(self, thread_pool, thread_gate, name=None):
| threading.Thread.__init__(self)
self.setDaemon(True)
self.exit_flag = False
self.__error = None
self.__traceback = None
self.__thread_pool = thread_pool
self.__work_queue = thread_pool.requeue
self.__thread_gate = thread_gate
if (not name):
self.__name = ('Anonymous_' + self.... |
'Perform the work of the thread.'
| def run(self):
| logger.debug('[%s] %s: started', self.getName(), self.__class__.__name__)
try:
self.WorkOnItems()
except:
self.SetError()
logger.debug('[%s] %s: exiting', self.getName(), self.__class__.__name__)
|
'Sets the error and traceback information for this thread.
This must be called from an exception handler.'
| def SetError(self):
| if (not self.__error):
exc_info = sys.exc_info()
self.__error = exc_info[1]
self.__traceback = exc_info[2]
logger.exception('[%s] %s:', self.getName(), self.__class__.__name__)
|
'Perform the work of a WorkerThread.'
| def WorkOnItems(self):
| while (not self.exit_flag):
item = None
self.__thread_gate.StartWork()
try:
(status, instruction) = (WorkItem.FAILURE, ThreadGate.DECREASE)
try:
if self.exit_flag:
instruction = ThreadGate.HOLD
break
... |
'If an error is present, then log it.'
| def CheckError(self):
| if self.__error:
logger.error('Error in %s: %s', self.getName(), self.__error)
if self.__traceback:
logger.debug('%s', ''.join(traceback.format_exception(self.__error.__class__, self.__error, self.__traceback)))
|
'Initialize an AdaptiveThreadPool.
An adaptive thread pool executes WorkItems using a number of
WorkerThreads. WorkItems represent items of work that may
succeed, soft fail, or hard fail. In addition, a completed work
item can signal this AdaptiveThreadPool to enable more or fewer
threads. Initially one thread is act... | def __init__(self, num_threads, queue_size=None, base_thread_name=None, worker_thread_factory=WorkerThread, queue_factory=Queue.Queue):
| if (queue_size is None):
queue_size = num_threads
self.requeue = ReQueue(queue_size, queue_factory=queue_factory)
self.__thread_gate = ThreadGate(num_threads)
self.__num_threads = num_threads
self.__threads = []
for i in xrange(num_threads):
thread = worker_thread_factory(self, s... |
'Return the number of threads in this thread pool.'
| def num_threads(self):
| return self.__num_threads
|
'Yields the registered threads.'
| def Threads(self):
| for thread in self.__threads:
(yield thread)
|
'Submit a WorkItem to the AdaptiveThreadPool.
Args:
item: A WorkItem instance.
block: Whether to block on submitting if the submit queue is full.
timeout: Time wait for room in the queue if block is True, 0.0 to
block indefinitely.
Raises:
Queue.Full if the submit queue is full.'
| def SubmitItem(self, item, block=True, timeout=0.0):
| self.requeue.put(item, block=block, timeout=timeout)
|
'Returns the number of items currently in the queue.'
| def QueuedItemCount(self):
| return self.requeue.qsize()
|
'Shutdown the thread pool.
Tasks may remain unexecuted in the submit queue.'
| def Shutdown(self):
| while (not self.requeue.empty()):
try:
unused_item = self.requeue.get_nowait()
self.requeue.task_done()
except Queue.Empty:
pass
for thread in self.__threads:
thread.exit_flag = True
self.requeue.put(_THREAD_SHOULD_EXIT)
self.__thread_gate.... |
'Wait until all work items have been completed.'
| def Wait(self):
| self.requeue.join()
|
'Wait for all threads to exit.'
| def JoinThreads(self):
| for thread in self.__threads:
logger.debug(('Waiting for %s to exit' % str(thread)))
thread.join()
|
'Output logs for any errors that occurred in the worker threads.'
| def CheckErrors(self):
| for thread in self.__threads:
thread.CheckError()
|
'Constructor for ThreadGate instances.
Args:
num_threads: The total number of threads using this gate.
sleep: Used for dependency injection.'
| def __init__(self, num_threads, sleep=InterruptibleSleep):
| self.__enabled_count = 1
self.__lock = threading.Lock()
self.__thread_semaphore = threading.Semaphore(self.__enabled_count)
self.__num_threads = num_threads
self.__backoff_time = 0
self.__sleep = sleep
|
'Enable one more worker thread.'
| def EnableThread(self):
| self.__lock.acquire()
try:
self.__enabled_count += 1
finally:
self.__lock.release()
self.__thread_semaphore.release()
|
'Enable all worker threads.'
| def EnableAllThreads(self):
| for unused_idx in xrange((self.__num_threads - self.__enabled_count)):
self.EnableThread()
|
'Starts a critical section in which the number of workers is limited.
Starts a critical section which allows self.__enabled_count
simultaneously operating threads. The critical section is ended by
calling self.FinishWork().'
| def StartWork(self):
| self.__thread_semaphore.acquire()
if (self.__backoff_time > 0.0):
if (not threading.currentThread().exit_flag):
logger.info('[%s] Backing off due to errors: %.1f seconds', threading.currentThread().getName(), self.__backoff_time)
self.__sleep(self.__backoff_t... |
'Ends a critical section started with self.StartWork().'
| def FinishWork(self, instruction=None):
| if ((not instruction) or (instruction == ThreadGate.HOLD)):
self.__thread_semaphore.release()
elif (instruction == ThreadGate.INCREASE):
if (self.__backoff_time > 0.0):
logger.info('Resetting backoff to 0.0')
self.__backoff_time = 0.0
do_enable = False
... |
'Perform the work of this work item and report the results.
Args:
thread_pool: The AdaptiveThreadPool instance associated with this
thread.
Returns:
A tuple (status, instruction) of the work status and an instruction
for the ThreadGate.'
| def PerformWork(self, thread_pool):
| raise NotImplementedError
|
'Initialize a WorkItemGenerator.
Args:
request_manager: A RequestManager instance with which to associate
WorkItems.
progress_queue: A progress queue with which to associate WorkItems.
progress_generator: A generator of progress information.
record_generator: A generator of data records.
skip_first: Whether to skip the... | def __init__(self, request_manager, progress_queue, progress_generator, record_generator, skip_first, batch_size):
| self.request_manager = request_manager
self.progress_queue = progress_queue
self.progress_generator = progress_generator
self.reader = record_generator
self.skip_first = skip_first
self.batch_size = batch_size
self.line_number = 1
self.column_count = None
self.read_rows = []
self... |
'Advance the reader to the given line.
Args:
line: A line number to advance to.'
| def _AdvanceTo(self, line):
| while (self.line_number < line):
self.reader.next()
self.line_number += 1
self.row_count += 1
self.xfer_count += 1
|
'Attempts to read and encode rows [key_start, key_end].
The encoded rows are stored in self.read_rows.
Args:
key_start: The starting line number.
key_end: The ending line number.
Raises:
StopIteration: if the reader runs out of rows
ResumeError: if there are an inconsistent number of columns.'
| def _ReadRows(self, key_start, key_end):
| assert (self.line_number == key_start)
self.read_rows = []
while (self.line_number <= key_end):
row = self.reader.next()
self.row_count += 1
if (self.column_count is None):
self.column_count = len(row)
self.read_rows.append((self.line_number, row))
self.li... |
'Makes a UploadWorkItem containing the given rows, with the given keys.
Args:
key_start: The start key for the UploadWorkItem.
key_end: The end key for the UploadWorkItem.
rows: A list of the rows for the UploadWorkItem.
progress_key: The progress key for the UploadWorkItem
Returns:
An UploadWorkItem instance for the g... | def _MakeItem(self, key_start, key_end, rows, progress_key=None):
| assert rows
item = UploadWorkItem(self.request_manager, self.progress_queue, rows, key_start, key_end, progress_key=progress_key)
return item
|
'Reads from the record_generator and generates UploadWorkItems.
Yields:
Instances of class UploadWorkItem
Raises:
ResumeError: If the progress database and data file indicate a different
number of rows.'
| def Batches(self):
| if self.skip_first:
logger.info('Skipping header line.')
try:
self.reader.next()
except StopIteration:
return
exhausted = False
self.line_number = 1
self.column_count = None
logger.info('Starting import; maximum %d entities per ... |
'Initializes a CSV generator.
Args:
csv_filename: File on disk containing CSV data.
openfile: Used for dependency injection of \'open\'.
create_csv_reader: Used for dependency injection of \'csv.reader\'.'
| def __init__(self, csv_filename, openfile=open, create_csv_reader=csv.reader):
| self.csv_filename = csv_filename
self.openfile = openfile
self.create_csv_reader = create_csv_reader
|
'Reads the CSV data file and generates row records.
Yields:
Lists of strings
Raises:
ResumeError: If the progress database and data file indicate a different
number of rows.'
| def Records(self):
| csv_file = self.openfile(self.csv_filename, 'rb')
reader = self.create_csv_reader(csv_file, skipinitialspace=True)
try:
for record in reader:
(yield record)
except csv.Error as e:
if (e.args and e.args[0].startswith('field larger than field limit')):
r... |
'Initialize the KeyRangeItemGenerator.
Args:
request_manager: A RequestManager instance.
kinds: The kind of entities being transferred, or a list of kinds.
progress_queue: A queue used for tracking progress information.
progress_generator: A generator of prior progress information, or None
if there is no prior status.
... | def __init__(self, request_manager, kinds, progress_queue, progress_generator, key_range_item_factory):
| self.request_manager = request_manager
if isinstance(kinds, basestring):
self.kinds = [kinds]
else:
self.kinds = kinds
self.row_count = 0
self.xfer_count = 0
self.progress_queue = progress_queue
self.progress_generator = progress_generator
self.key_range_item_factory = ke... |
'Iterate through saved progress information.
Yields:
KeyRangeItem instances corresponding to undownloaded key ranges.'
| def Batches(self):
| if (self.progress_generator is not None):
for (progress_key, state, kind, key_start, key_end) in self.progress_generator:
if ((state is not None) and (state != STATE_GOT) and (key_start is not None)):
key_start = ParseKey(key_start)
key_end = ParseKey(key_end)
... |
'Returns the list of entities for this result in key order.'
| def Entities(self):
| if (self.direction == key_range_module.KeyRange.ASC):
return list(self.entities)
else:
result = list(self.entities)
result.reverse()
return result
|
'Initialize the _WorkItem instance.
Args:
progress_queue: A queue used for tracking progress information.
key_start: The start key of the work item.
key_end: The end key of the work item.
state_namer: Function to describe work item states.
state: The initial state of the work item.
progress_key: If this WorkItem repres... | def __init__(self, progress_queue, key_start, key_end, state_namer, state=STATE_READ, progress_key=None):
| adaptive_thread_pool.WorkItem.__init__(self, ('[%s-%s]' % (key_start, key_end)))
self.progress_queue = progress_queue
self.state_namer = state_namer
self.state = state
self.progress_key = progress_key
self.progress_event = threading.Event()
self.key_start = key_start
self.key_end = key_e... |
'Sets the error and traceback information for this thread.
This must be called from an exception handler.'
| def SetError(self):
| if (not self.error):
exc_info = sys.exc_info()
self.error = exc_info[1]
self.traceback = exc_info[2]
|
'Perform the work of this work item and report the results.
Args:
thread_pool: An AdaptiveThreadPool instance.
Returns:
A tuple (status, instruction) of the work status and an instruction
for the ThreadGate.'
| def PerformWork(self, thread_pool):
| status = adaptive_thread_pool.WorkItem.FAILURE
instruction = adaptive_thread_pool.ThreadGate.DECREASE
try:
self.MarkAsTransferring()
try:
transfer_time = self._TransferItem(thread_pool)
if (transfer_time is None):
status = adaptive_thread_pool.WorkItem... |
'Raises an Error if the state of this range is not in states.'
| def _AssertInState(self, *states):
| if (not (self.state in states)):
raise BadStateError(('%s:%s not in %s' % (str(self), self.state_namer(self.state), map(self.state_namer, states))))
|
'Raises an Error if the progress key is None.'
| def _AssertProgressKey(self):
| if (self.progress_key is None):
raise BadStateError(('%s: Progress key is missing' % str(self)))
|
'Mark this _WorkItem as read, updating the progress database.'
| def MarkAsRead(self):
| self._AssertInState(STATE_READ)
self._StateTransition(STATE_READ, blocking=True)
|
'Mark this _WorkItem as transferring, updating the progress database.'
| def MarkAsTransferring(self):
| self._AssertInState(STATE_READ, STATE_ERROR)
self._AssertProgressKey()
self._StateTransition(STATE_GETTING, blocking=True)
|
'Mark this _WorkItem as transferred, updating the progress database.'
| def MarkAsTransferred(self):
| raise NotImplementedError()
|
'Mark this _WorkItem as failed, updating the progress database.'
| def MarkAsError(self):
| self._AssertInState(STATE_GETTING)
self._AssertProgressKey()
self._StateTransition(STATE_ERROR, blocking=True)
|
'Transition the work item to a new state, storing progress information.
Args:
new_state: The state to transition to.
blocking: Whether to block for the progress thread to acknowledge the
transition.'
| def _StateTransition(self, new_state, blocking=False):
| assert (not self.progress_event.isSet())
self.state = new_state
self.progress_queue.put(self)
if blocking:
self.progress_event.wait()
self.progress_event.clear()
|
'Initialize the UploadWorkItem instance.
Args:
request_manager: A RequestManager instance.
progress_queue: A queue used for tracking progress information.
rows: A list of pairs of a line number and a list of column values.
key_start: The (numeric) starting key, inclusive.
key_end: The (numeric) ending key, inclusive.
p... | def __init__(self, request_manager, progress_queue, rows, key_start, key_end, progress_key=None):
| _WorkItem.__init__(self, progress_queue, key_start, key_end, ImportStateName, state=STATE_READ, progress_key=progress_key)
assert isinstance(key_start, (int, long))
assert isinstance(key_end, (int, long))
assert (key_start <= key_end)
self.request_manager = request_manager
self.rows = rows
s... |
'Transfers the entities associated with an item.
Args:
thread_pool: An AdaptiveThreadPool instance.
get_time: Used for dependency injection.'
| def _TransferItem(self, thread_pool, get_time=time.time):
| t = get_time()
if (not self.content):
self.content = self.request_manager.EncodeContent(self.rows)
try:
self.request_manager.PostEntities(self.content)
except:
raise
return (get_time() - t)
|
'Mark this UploadWorkItem as sucessfully-sent to the server.'
| def MarkAsTransferred(self):
| self._AssertInState(STATE_SENDING)
self._AssertProgressKey()
self._StateTransition(STATE_SENT, blocking=False)
|
'Initialize a KeyRangeItem object.
Args:
request_manager: A RequestManager instance.
progress_queue: A queue used for tracking progress information.
kind: The kind of entities for this range.
key_range: A KeyRange instance for this work item.
progress_key: The key for this range within the progress database.
state: The... | def __init__(self, request_manager, progress_queue, kind, key_range, progress_key=None, state=STATE_READ, first=False):
| _WorkItem.__init__(self, progress_queue, key_range.key_start, key_range.key_end, ExportStateName, state=state, progress_key=progress_key)
assert KeyLEQ(key_range.key_start, key_range.key_end), ('%s not less than %s' % (repr(key_range.key_start), repr(key_range.key_end)))
self.request_manager = r... |
'Mark this KeyRangeItem as transferred, updating the progress database.'
| def MarkAsTransferred(self):
| pass
|
'Mark this KeyRangeItem as success, updating the progress database.
Process will split this KeyRangeItem based on the content of
download_result and adds the unfinished ranges to the work queue.
Args:
download_result: A DownloadResult instance.
thread_pool: An AdaptiveThreadPool instance.
batch_size: The number of enti... | def Process(self, download_result, thread_pool, batch_size, new_state=STATE_GOT):
| self._AssertInState(STATE_GETTING)
self._AssertProgressKey()
self.download_result = download_result
self.count = len(download_result.keys)
if download_result.continued:
self._FinishedRange()._StateTransition(new_state, blocking=True)
self._AddUnfinishedRanges(thread_pool, batch_size)... |
'Returns the range completed by the download_result.
Returns:
A KeyRangeItem representing a completed range.'
| def _FinishedRange(self):
| assert (self.download_result is not None)
if (self.key_range.direction == key_range_module.KeyRange.ASC):
key_start = self.key_range.key_start
if self.download_result.continued:
key_end = self.download_result.key_end
else:
key_end = self.key_range.key_end
else... |
'Split the key range [key_start, key_end] into a list of ranges.'
| def _SplitAndAddRanges(self, thread_pool, batch_size):
| if (self.download_result.direction == key_range_module.KeyRange.ASC):
key_range = KeyRange(key_start=self.download_result.key_end, key_end=self.key_range.key_end, include_start=False)
else:
key_range = KeyRange(key_start=self.key_range.key_start, key_end=self.download_result.key_start, include_e... |
'Adds incomplete KeyRanges to the thread_pool.
Args:
thread_pool: An AdaptiveThreadPool instance.
batch_size: The number of entities to transfer per request.
Returns:
A list of KeyRanges representing incomplete datastore key ranges.
Raises:
KeyRangeError: if this key range has already been completely transferred.'
| def _AddUnfinishedRanges(self, thread_pool, batch_size):
| assert (self.download_result is not None)
if self.download_result.continued:
self._SplitAndAddRanges(thread_pool, batch_size)
else:
raise KeyRangeError('No unfinished part of key range.')
|
'Transfers the entities associated with an item.'
| def _TransferItem(self, thread_pool, get_time=time.time):
| t = get_time()
download_result = self.request_manager.GetEntities(self, retry_parallel=self.first)
transfer_time = (get_time() - t)
self.Process(download_result, thread_pool, self.request_manager.batch_size)
return transfer_time
|
'Initialize a RequestManager object.
Args:
app_id: String containing the application id for requests.
host_port: String containing the "host:port" pair; the port is optional.
url_path: partial URL (path) to post entity data to.
kind: Kind of the Entity records being posted.
throttle: A Throttle instance.
batch_size: Th... | def __init__(self, app_id, host_port, url_path, kind, throttle, batch_size, secure, email, passin, dry_run=False, server=None, throttle_class=None):
| self.app_id = app_id
self.host_port = host_port
self.host = host_port.split(':')[0]
if (url_path and (url_path[0] != '/')):
url_path = ('/' + url_path)
self.url_path = url_path
self.kind = kind
self.throttle = throttle
self.batch_size = batch_size
self.secure = secure
sel... |
'Invoke authentication if necessary.'
| def Authenticate(self):
| logger.info('Connecting to %s%s', self.host_port, self.url_path)
if self.dry_run:
self.authenticated = True
return
remote_api_stub.MaybeInvokeAuthentication()
self.authenticated = True
|
'Prompts the user for a username and password.
Caches the results the first time it is called and returns the
same result every subsequent time.
Args:
raw_input_fn: Used for dependency injection.
password_input_fn: Used for dependency injection.
Returns:
A pair of the username and password.'
| def AuthFunction(self, raw_input_fn=raw_input, password_input_fn=getpass.getpass):
| self.auth_called = True
return _AuthFunction(self.host, self.email, self.passin, raw_input_fn, password_input_fn)
|
'Increment the unique id counter associated with ancestor_path and kind.
Args:
ancestor_path: A list encoding the path of a key.
kind: The string name of a kind.
high_id: The int value to which to increment the unique id counter.'
| def IncrementId(self, ancestor_path, kind, high_id):
| if self.dry_run:
return
high_id_key = datastore.Key.from_path(*(ancestor_path + [kind, high_id]))
IncrementId(high_id_key)
|
'Returns the list of kinds for this app.'
| def GetSchemaKinds(self):
| global_stat = stats.GlobalStat.all().get()
if (not global_stat):
raise KindStatError()
timestamp = global_stat.timestamp
kind_stat = stats.KindStat.all().filter('timestamp =', timestamp).fetch(1000)
kind_list = [stat.kind_name for stat in kind_stat if (stat.kind_name and (not stat.kind_na... |
'Encodes row data to the wire format.
Args:
rows: A list of pairs of a line number and a list of column values.
loader: Used for dependency injection.
Returns:
A list of datastore.Entity instances.
Raises:
ConfigurationError: if no loader is defined for self.kind'
| def EncodeContent(self, rows, loader=None):
| if (not loader):
try:
loader = Loader.RegisteredLoader(self.kind)
except KeyError:
logger.error(('No Loader defined for kind %s.' % self.kind))
raise ConfigurationError(('No Loader defined for kind %s.' % self.kind))
entities = []... |
'Posts Entity records to a remote endpoint over HTTP.
Args:
entities: A list of datastore entities.'
| def PostEntities(self, entities):
| if self.dry_run:
return
datastore.Put(entities)
|
'Perform the given query and return a list of entity_pb\'s.'
| def _QueryForPbs(self, query):
| try:
query_pb = query._ToPb(limit=self.batch_size, count=self.batch_size)
result_pb = datastore_pb.QueryResult()
apiproxy_stub_map.MakeSyncCall('datastore_v3', 'RunQuery', query_pb, result_pb)
results = result_pb.result_list()
while result_pb.more_results():
next_... |
'Gets Entity records from a remote endpoint over HTTP.
Args:
key_range_item: Range of keys to get.
key_factory: Used for dependency injection.
keys_only: bool, default False, only get keys values
retry_parallel: bool, default False, to try a parallel download despite
past parallel download failures.
Returns:
A Download... | def GetEntities(self, key_range_item, key_factory=datastore.Key, keys_only=False, retry_parallel=False):
| keys = []
entities = []
kind = key_range_item.kind
if retry_parallel:
self.parallel_download = True
if self.parallel_download:
query = key_range_item.key_range.make_directed_datastore_query(kind, keys_only=keys_only)
try:
results = self._QueryForPbs(query)
... |
'Returns a mapper for the registered kind.
Returns:
A Mapper instance.
Raises:
ConfigurationError: if no Mapper is defined for kind'
| def GetMapper(self, kind):
| if (not self.mapper):
try:
self.mapper = Mapper.RegisteredMapper(kind)
except KeyError:
logger.error(('No Mapper defined for kind %s.' % kind))
raise ConfigurationError(('No Mapper defined for kind %s.' % kind))
return self.mapper... |
'Perform the work of the thread.'
| def run(self):
| logger.debug('[%s] %s: started', self.getName(), self.__class__.__name__)
try:
self.PerformWork()
except:
self.SetError()
logger.exception('[%s] %s:', self.getName(), self.__class__.__name__)
logger.debug('[%s] %s: exiting', self.getName(), self.__class__.__name__)... |
'Sets the error and traceback information for this thread.
This must be called from an exception handler.'
| def SetError(self):
| if (not self.error):
exc_info = sys.exc_info()
self.error = exc_info[1]
self.traceback = exc_info[2]
|
'Perform the thread-specific work.'
| def PerformWork(self):
| raise NotImplementedError()
|
'If an error is present, then log it.'
| def CheckError(self):
| if self.error:
logger.error('Error in %s: %s', self.GetFriendlyName(), self.error)
if self.traceback:
logger.debug(''.join(traceback.format_exception(self.error.__class__, self.error, self.traceback)))
|
'Returns a human-friendly description of the thread.'
| def GetFriendlyName(self):
| if hasattr(self, 'NAME'):
return self.NAME
return 'unknown thread'
|
'Initialize the DataSourceThread instance.
Args:
request_manager: A RequestManager instance.
kinds: The kinds of entities being transferred.
thread_pool: An AdaptiveThreadPool instance.
progress_queue: A queue used for tracking progress information.
workitem_generator_factory: A factory that creates a WorkItem generato... | def __init__(self, request_manager, kinds, thread_pool, progress_queue, workitem_generator_factory, progress_generator_factory):
| _ThreadBase.__init__(self)
self.request_manager = request_manager
self.kinds = kinds
self.thread_pool = thread_pool
self.progress_queue = progress_queue
self.workitem_generator_factory = workitem_generator_factory
self.progress_generator_factory = progress_generator_factory
self.entity_c... |
'Performs the work of a DataSourceThread.'
| def PerformWork(self):
| if self.progress_generator_factory:
progress_gen = self.progress_generator_factory()
else:
progress_gen = None
content_gen = self.workitem_generator_factory(self.request_manager, self.progress_queue, progress_gen, self.kinds)
self.xfer_count = 0
self.read_count = 0
self.read_all ... |
'Initialize the _Database instance.
Args:
db_filename: The sqlite3 file to use for the database.
create_table: A string containing the SQL table creation command.
signature: A string identifying the important invocation options,
used to make sure we are not using an old database.
index: An optional string to create an ... | def __init__(self, db_filename, create_table, signature, index=None, commit_periodicity=100):
| self.db_filename = db_filename
logger.info('Opening database: %s', db_filename)
self.primary_conn = sqlite3.connect(db_filename, isolation_level=None)
self.primary_thread = threading.currentThread()
self.secondary_conn = None
self.secondary_thread = None
self.operation_count = 0
se... |
'Finalize any operations the secondary thread has performed.
The database aggregates lots of operations into a single commit, and
this method is used to commit any pending operations as the thread
is about to shut down.'
| def ThreadComplete(self):
| if self.secondary_conn:
self._MaybeCommit(force_commit=True)
|
'Periodically commit changes into the SQLite database.
Committing every operation is quite expensive, and slows down the
operation of the script. Thus, we only commit after every N operations,
as determined by the self.commit_periodicity value. Optionally, the
caller can force a commit.
Args:
force_commit: Pass True in... | def _MaybeCommit(self, force_commit=False):
| self.operation_count += 1
if (force_commit or ((self.operation_count % self.commit_periodicity) == 0)):
self.secondary_conn.commit()
|
'Possibly open a database connection for the secondary thread.
If the connection is not open (for the calling thread, which is assumed
to be the unique secondary thread), then open it. We also open a couple
cursors for later use (and reuse).'
| def _OpenSecondaryConnection(self):
| if self.secondary_conn:
return
assert (not _RunningInThread(self.primary_thread))
self.secondary_thread = threading.currentThread()
self.secondary_conn = sqlite3.connect(self.db_filename)
self.insert_cursor = self.secondary_conn.cursor()
self.update_cursor = self.secondary_conn.cursor()
|
'Initialize a ResultDatabase object.
Args:
db_filename: The name of the SQLite database to use.
signature: A string identifying the important invocation options,
used to make sure we are not using an old database.
commit_periodicity: How many operations to perform between commits.
exporter: Exporter instance; if export... | def __init__(self, db_filename, signature, commit_periodicity=1, exporter=None):
| self.complete = False
create_table = 'create table result (\nid BLOB primary key,\nvalue BLOB not null,\nsort_key BLOB)'
_Database.__init__(self, db_filename, create_table, signature, commit_periodicity=commit_periodicity)
if self.existing_table:
cursor = self.prima... |
'Store an entity in the result database.
Args:
entity_id: A datastore.Key for the entity.
entity: The entity to store.
Returns:
True if this entities is not already present in the result database.'
| def _StoreEntity(self, entity_id, entity):
| assert _RunningInThread(self.secondary_thread)
assert isinstance(entity_id, datastore.Key), ('expected a datastore.Key, got a %s' % entity_id.__class__.__name__)
key_str = buffer(KeyStr(entity_id).encode('utf-8'))
self.insert_cursor.execute('select count(*) from result where ... |
'Store a group of entities in the result database.
Args:
keys: A list of entity keys.
entities: A list of entities.
Returns:
The number of new entities stored in the result database.'
| def StoreEntities(self, keys, entities):
| self._OpenSecondaryConnection()
t = time.time()
count = 0
for (entity_id, entity) in zip(keys, entities):
if self._StoreEntity(entity_id, entity):
count += 1
logger.debug('%s insert: delta=%.3f', self.db_filename, (time.time() - t))
logger.debug('Entities transferred... |
'Marks the result database as containing complete results.'
| def ResultsComplete(self):
| self.complete = True
|
'Yields all pairs of (id, value) from the result table.'
| def AllEntities(self):
| conn = sqlite3.connect(self.db_filename, isolation_level=None)
cursor = conn.cursor()
cursor.execute('select id, value from result order by sort_key, id')
for (unused_entity_id, entity) in cursor:
entity_proto = entity_pb.EntityProto(contents=entity)
(yield datast... |
'Initialize the ProgressDatabase instance.
Args:
db_filename: The name of the SQLite database to use.
sql_type: A string of the SQL type to use for entity keys.
py_type: The python type of entity keys.
signature: A string identifying the important invocation options,
used to make sure we are not using an old database.
... | def __init__(self, db_filename, sql_type, py_type, signature, commit_periodicity=100):
| self.prior_key_end = None
create_table = ('create table progress (\nid integer primary key autoincrement,\nstate integer not null,\nkind text not null,\nkey_start %s,\nkey_end %s)' % (sql_type, sql_type))
self.py_type = py_type
index = 'create index i_s... |
'Returns True if the database has progress information.
Note there are two basic cases for progress information:
1) All saved records indicate a successful upload. In this case, we
need to skip everything transmitted so far and then send the rest.
2) Some records for incomplete transfer are present. These need to be
se... | def UseProgressData(self):
| assert _RunningInThread(self.primary_thread)
cursor = self.primary_conn.cursor()
cursor.execute('select count(*) from progress')
row = cursor.fetchone()
if (row is None):
raise ResumeError('Cannot retrieve progress information from database.')
return (row[0] != 0)... |
'Record a new progress record, returning a key for later updates.
The specified progress information will be persisted into the database.
A unique key will be returned that identifies this progress state. The
key is later used to (quickly) update this record.
For the progress resumption to proceed properly, calls to St... | def StoreKeys(self, kind, key_start, key_end):
| self._OpenSecondaryConnection()
assert _RunningInThread(self.secondary_thread)
assert ((not key_start) or isinstance(key_start, self.py_type)), ('%s is a %s, %s expected %s' % (key_start, key_start.__class__, self.__class__.__name__, self.py_type))
assert ((not key_end) or isinstance(k... |
'Update a specified progress record with new information.
Args:
key: The key for this progress record, returned from StoreKeys
new_state: The new state to associate with this progress record.'
| def UpdateState(self, key, new_state):
| self._OpenSecondaryConnection()
assert _RunningInThread(self.secondary_thread)
assert isinstance(new_state, int)
self.update_cursor.execute('update progress set state=? where id=?', (new_state, key))
self._MaybeCommit()
|
'Delete the entities with the given key from the result database.'
| def DeleteKey(self, progress_key):
| self._OpenSecondaryConnection()
assert _RunningInThread(self.secondary_thread)
t = time.time()
self.insert_cursor.execute('delete from progress where rowid = ?', (progress_key,))
logger.debug('delete: delta=%.3f', (time.time() - t))
self._MaybeCommit()
|
'Get a generator which yields progress information.
The returned generator will yield a series of 5-tuples that specify
progress information about a prior run of the uploader. The 5-tuples
have the following values:
progress_key: The unique key to later update this record with new
progress information.
state: The last ... | def GetProgressStatusGenerator(self):
| conn = sqlite3.connect(self.db_filename, isolation_level=None)
cursor = conn.cursor()
cursor.execute('select max(key_end) from progress')
result = cursor.fetchone()
if (result is not None):
key_end = result[0]
else:
logger.debug('No rows in progress database.... |
'Initialize an ExportProgressDatabase.'
| def __init__(self, db_filename, signature):
| _ProgressDatabase.__init__(self, db_filename, 'TEXT', datastore.Key, signature, commit_periodicity=1)
|
'Check if the progress database contains progress data.
Returns:
True: if the database contains progress data.'
| def UseProgressData(self):
| return self.existing_table
|
'Whether the stub database has progress information (it doesn\'t).'
| def UseProgressData(self):
| return False
|
'Pretend to store a key in the stub database.'
| def StoreKeys(self, unused_kind, unused_key_start, unused_key_end):
| return 'fake-key'
|
'Pretend to update the state of a progress item.'
| def UpdateState(self, unused_key, unused_new_state):
| pass
|
'Finalize operations on the stub database (i.e. do nothing).'
| def ThreadComplete(self):
| pass
|
'Delete the operations with a given key (but, do nothing.)'
| def DeleteKey(self, unused_key):
| pass
|
'Initialize the ProgressTrackerThread instance.
Args:
progress_queue: A Queue used for tracking progress information.
progress_db: The database for tracking progress information; should
be an instance of ProgressDatabase.'
| def __init__(self, progress_queue, progress_db):
| _ThreadBase.__init__(self)
self.progress_queue = progress_queue
self.db = progress_db
self.entities_transferred = 0
|
'Return the total number of unique entities transferred.'
| def EntitiesTransferred(self):
| return self.entities_transferred
|
'Updates the progress information for the given item.
Args:
item: A work item whose new state will be recorded'
| def UpdateProgress(self, item):
| raise NotImplementedError()
|
'Performs final actions after the entity transfer is complete.'
| def WorkFinished(self):
| raise NotImplementedError()
|
'Performs the work of a ProgressTrackerThread.'
| def PerformWork(self):
| while (not self.exit_flag):
try:
item = self.progress_queue.get(block=True, timeout=1.0)
except Queue.Empty:
continue
if (item == _THREAD_SHOULD_EXIT):
break
if ((item.state == STATE_READ) and (item.progress_key is None)):
item.progress... |
'Initialize the ProgressTrackerThread instance.
Args:
progress_queue: A Queue used for tracking progress information.
progress_db: The database for tracking progress information; should
be an instance of ProgressDatabase.'
| def __init__(self, progress_queue, progress_db):
| _ProgressThreadBase.__init__(self, progress_queue, progress_db)
|
'Update the state of the given WorkItem.
Args:
item: A WorkItem instance.'
| def UpdateProgress(self, item):
| self.db.UpdateState(item.progress_key, item.state)
if (item.state == STATE_SENT):
self.entities_transferred += item.count
|
'Performs final actions after the entity transfer is complete.'
| def WorkFinished(self):
| pass
|
'Initialize the ExportProgressThread instance.
Args:
exporter: An Exporter instance for the download.
progress_queue: A Queue used for tracking progress information.
progress_db: The database for tracking progress information; should
be an instance of ProgressDatabase.
result_db: The database for holding exported entit... | def __init__(self, exporter, progress_queue, progress_db, result_db):
| _ProgressThreadBase.__init__(self, progress_queue, progress_db)
self.exporter = exporter
self.existing_count = result_db.existing_count
self.result_db = result_db
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.