ArielGlenn has submitted this change and it was merged.
Change subject: some flake8 for worker.py and related files
......................................................................
some flake8 for worker.py and related files
whitespace, is (not) None, blank lines, indentation
Change-Id: Ib0063be4981a2b34a99375e9dc08bff8a46ec45f
---
M xmldumps-backup/dumps/CommandManagement.py
M xmldumps-backup/dumps/WikiDump.py
M xmldumps-backup/dumps/exceptions.py
M xmldumps-backup/dumps/fileutils.py
M xmldumps-backup/dumps/jobs.py
M xmldumps-backup/dumps/runnerutils.py
M xmldumps-backup/dumps/utils.py
M xmldumps-backup/monitor.py
M xmldumps-backup/worker.py
M xmldumps-backup/xmlabstracts.py
M xmldumps-backup/xmllogs.py
M xmldumps-backup/xmlstreams.py
M xmldumps-backup/xmlstubs.py
13 files changed, 183 insertions(+), 137 deletions(-)
Approvals:
ArielGlenn: Verified; Looks good to me, approved
jenkins-bot: Verified
diff --git a/xmldumps-backup/dumps/CommandManagement.py
b/xmldumps-backup/dumps/CommandManagement.py
index 6030bf3..e627a22 100644
--- a/xmldumps-backup/dumps/CommandManagement.py
+++ b/xmldumps-backup/dumps/CommandManagement.py
@@ -10,6 +10,7 @@
# FIXME no explicit stderr handling, is this ok?
+
class CommandPipeline(object):
"""Run a series of commands in a pipeline, e.g. ps -ef | grep convert
The pipeline can be one command long (in which case nothing special
happens)
@@ -145,7 +146,7 @@
# will hang forever in the wait() on them.
self._processes.reverse()
for proc in self._processes:
- print "DEBUG: trying to get return code for %s" % proc.pid
+ print "DEBUG: trying to get return code for %s" % proc.pid
self._exit_values.append(proc.wait())
retcode = proc.poll()
print "DEBUG: return code %s for %s" % (retcode, proc.pid)
@@ -154,12 +155,11 @@
if self.save_file():
self.save_file().close()
-
def is_running(self):
"""Check if process is running."""
# Note that poll() returns None if the process
# is not completed, or some value (may be 0) otherwise
- if self._last_process_in_pipe.poll() == None:
+ if self._last_process_in_pipe.poll() is None:
return True
else:
return False
@@ -213,7 +213,7 @@
# this means we never had a poll return with
# activity on the current object... which counts as false
return False
- if self._last_poll_state & (select.POLLIN|select.POLLPRI):
+ if self._last_poll_state & (select.POLLIN | select.POLLPRI):
return True
else:
return False
@@ -240,11 +240,11 @@
if not self._poller:
self._poller = select.poll()
- self._poller.register(self._last_process_in_pipe.stdout,
select.POLLIN|select.POLLPRI)
+ self._poller.register(self._last_process_in_pipe.stdout,
select.POLLIN | select.POLLPRI)
# FIXME we should return something reasonable if we
# unregistered this the last time
- if timeout == None:
+ if timeout is None:
fd_ready = self._poller.poll()
else:
# FIXME so poll doesn't take an arg :-P ...?
@@ -273,7 +273,6 @@
# if (out):
# sys.stdout.write("DEBUG: got from %s out %s" % (
# self._lastCommandString, out))
-
signal.alarm(0)
return out
@@ -311,6 +310,7 @@
self.start_commands()
self.get_all_output()
self.set_return_codes()
+
class CommandSeries(object):
"""Run a list of command pipelines in serial (e.g.
@@ -358,7 +358,7 @@
for pipeline in self._command_pipelines:
if not pipeline.exited_successfully():
command = pipeline.exited_with_errors()
- if command != None:
+ if command is not None:
commands.append(command)
return commands
@@ -411,6 +411,7 @@
# if self.all_commands_completed() and not
len(self._processes_to_poll):
# break
+
class ProcessMonitor(threading.Thread):
def __init__(self, timeout, queue, output_queue, default_callback_interval,
callback_stderr, callbackStdout, callback_timed,
@@ -433,12 +434,12 @@
while series.process_producing_output():
proc = series.process_producing_output()
poller = select.poll()
- poller.register(proc.stderr, select.POLLIN|select.POLLPRI)
+ poller.register(proc.stderr, select.POLLIN | select.POLLPRI)
fderr = proc.stderr.fileno()
flerr = fcntl.fcntl(fderr, fcntl.F_GETFL)
fcntl.fcntl(fderr, fcntl.F_SETFL, flerr | os.O_NONBLOCK)
if proc.stdout:
- poller.register(proc.stdout, select.POLLIN|select.POLLPRI)
+ poller.register(proc.stdout, select.POLLIN | select.POLLPRI)
fdout = proc.stdout.fileno()
flout = fcntl.fcntl(fdout, fcntl.F_GETFL)
fcntl.fcntl(fdout, fcntl.F_SETFL, flout | os.O_NONBLOCK)
@@ -488,6 +489,7 @@
# completed the whole series. time to go home.
self.queue.task_done()
+
class OutputQueueItem(object):
def __init__(self, channel, contents):
self.channel = channel
@@ -503,6 +505,7 @@
get_stdout_channel = staticmethod(get_stdout_channel)
get_stderr_channel = staticmethod(get_stderr_channel)
+
class CommandsInParallel(object):
"""Run a pile of commandSeries in parallel (e.g. dump articles 1 to 100K,
@@ -597,7 +600,7 @@
self._callback_stdout(output.contents)
else:
sys.stderr.write(output.contents)
- else: # output channel is stderr
+ else: # output channel is stderr
if self._callback_stderr:
if self._callback_stderr_arg:
self._callback_stderr(self._callback_stderr_arg,
output.contents)
@@ -615,12 +618,13 @@
def testcallback(output=None):
output_file = open("/home/ariel/src/mediawiki/testing/outputsaved.txt",
"a")
- if output == None:
+ if output is None:
output_file.write("no output for me.\n")
else:
output_file.write(output)
output_file.close()
+
def main():
command1 = ["/usr/bin/vmstat", "1", "10"]
command2 = ["/usr/sbin/lnstat", "-i", "7", "-c", "5", "-k",
diff --git a/xmldumps-backup/dumps/WikiDump.py
b/xmldumps-backup/dumps/WikiDump.py
index 6c58911..18ef7e9 100644
--- a/xmldumps-backup/dumps/WikiDump.py
+++ b/xmldumps-backup/dumps/WikiDump.py
@@ -10,6 +10,7 @@
import time
import tempfile
+
class FileUtils(object):
def fileAge(filename):
@@ -118,6 +119,7 @@
_prettySize = staticmethod(_prettySize)
fileInfo = staticmethod(fileInfo)
+
class TimeUtils(object):
def today():
@@ -133,6 +135,7 @@
today = staticmethod(today)
prettyTime = staticmethod(prettyTime)
prettyDate = staticmethod(prettyDate)
+
class MiscUtils(object):
def dbList(filename):
@@ -162,6 +165,7 @@
dbList = staticmethod(dbList)
shellEscape = staticmethod(shellEscape)
+
class Config(object):
def __init__(self, config_file=False):
self.projectName = False
@@ -174,37 +178,37 @@
"/etc/wikidump.conf",
os.path.join(os.getenv("HOME"), ".wikidump.conf")]
defaults = {
- #"wiki": {
+ # "wiki": {
"dblist": "",
"privatelist": "",
"flaggedrevslist": "",
"wikidatalist": "",
"globalusagelist": "",
"wikidataclientlist": "",
- #"dir": "",
+ # "dir": "",
"forcenormal": "0",
"halt": "0",
- "skipdblist" : "",
- #"output": {
+ "skipdblist": "",
+ # "output": {
"public": "/dumps/public",
"private": "/dumps/private",
- "temp":"/dumps/temp",
+ "temp": "/dumps/temp",
"webroot": "http://localhost/dumps",
"index": "index.html",
"templatedir": home,
"perdumpindex": "index.html",
"logfile": "dumplog.txt",
"fileperms": "0640",
- #"reporting": {
+ # "reporting": {
"adminmail": "root@localhost",
"mailfrom": "root@localhost",
"smtpserver": "localhost",
"staleage": "3600",
- #"database": {
+ # "database": {
# these are now set in getDbUserAndPassword() if needed
"user": "",
"password": "",
- #"tools": {
+ # "tools": {
"php": "/bin/php",
"gzip": "/usr/bin/gzip",
"bzip2": "/usr/bin/bzip2",
@@ -218,33 +222,33 @@
"checkforbz2footer": "/usr/local/bin/checkforbz2footer",
"writeuptopageid": "/usr/local/bin/writeuptopageid",
"recompressxml": "/usr/local/bin/recompressxml",
- #"cleanup": {
+ # "cleanup": {
"keep": "3",
- #"chunks": {
+ # "chunks": {
# set this to 1 to enable runing the various xml dump stages as
chunks in parallel
- "chunksEnabled" : "0",
+ "chunksEnabled": "0",
# for page history runs, number of pages for each chunk, specified
separately
# e.g.
"1000,10000,100000,2000000,2000000,2000000,2000000,2000000,2000000,2000000"
# would define 10 chunks with the specified number of pages in
each and any extra in
# a final 11th chunk
- "pagesPerChunkHistory" : False,
+ "pagesPerChunkHistory": False,
# revs per chunk (roughly, it will be split along page lines)
# for history and current dumps
# values: positive integer, "compute",
# this field is overriden by pagesPerChunkHistory
# CURRENTLY NOT COMPLETE so please don't use this.
- "revsPerChunkHistory" : False,
+ "revsPerChunkHistory": False,
# pages per chunk for abstract runs
- "pagesPerChunkAbstract" : False,
+ "pagesPerChunkAbstract": False,
# number of chunks for abstract dumps, overrides
pagesPerChunkAbstract
- "chunksForAbstract" : 0,
+ "chunksForAbstract": 0,
# whether or not to recombine the history pieces
- "recombineHistory" : "1",
+ "recombineHistory": "1",
# do we write out checkpoint files at regular intervals?
# (article/metacurrent/metahistory dumps only.)
- "checkpointTime" : "0",
- #"otherformats": {
- "multistream" : "0",
+ "checkpointTime": "0",
+ # "otherformats": {
+ "multistream": "0",
}
self.conf = ConfigParser.SafeConfigParser(defaults)
self.conf.read(self.files)
@@ -261,7 +265,7 @@
self.dbPassword = None
self.parseConfFileGlobally()
self.parseConfFilePerProject()
- self.getDbUserAndPassword() # get from MW adminsettings file if not
set in conf file
+ self.getDbUserAndPassword() # get from MW adminsettings file if not
set in conf file
def parsePHPAssignment(self, line):
# not so much parse as grab a string to the right of the equals sign,
@@ -279,7 +283,7 @@
# them in the conf file; failing that we fall back on defaults
specified
# here
- if self.dbUser: # already set via conf file, don't override
+ if self.dbUser: # already set via conf file, don't override
return
default_dbuser = "root"
@@ -472,7 +476,7 @@
dump_failed = (status == '') or ('dump aborted' in status)
available.append((dump_failed, date, age, db))
available.sort()
- return [db for (failed, date, age, db) in available]
+ return [db for (_failed, _date, _age, db) in available]
def readTemplate(self, name):
template = os.path.join(self.templateDir, name)
@@ -592,7 +596,6 @@
self.unlock()
def writePerDumpIndex(self, html):
- directory = os.path.join(self.publicDir(), self.date)
index = os.path.join(self.publicDir(), self.date,
self.config.perDumpIndex)
FileUtils.writeFileInPlace(index, html, self.config.fileperms)
@@ -601,7 +604,6 @@
return os.path.exists(index)
def writeStatus(self, message):
- directory = os.path.join(self.publicDir(), self.date)
index = os.path.join(self.publicDir(), self.date, "status.html")
FileUtils.writeFileInPlace(index, message, self.config.fileperms)
@@ -677,6 +679,7 @@
def lockAge(self):
return FileUtils.fileAge(self.lockFile())
+
class LockWatchdog(threading.Thread):
"""Touch the given file every 10 seconds until asked to stop."""
@@ -713,6 +716,7 @@
"""Run me inside..."""
os.utime(self.lockfile, None)
+
def cleanup():
"""Call cleanup handlers for any background threads..."""
for watchdog in LockWatchdog.threads:
diff --git a/xmldumps-backup/dumps/exceptions.py
b/xmldumps-backup/dumps/exceptions.py
index 517517e..0a178e2 100644
--- a/xmldumps-backup/dumps/exceptions.py
+++ b/xmldumps-backup/dumps/exceptions.py
@@ -1,8 +1,9 @@
# dump-specific exceptions
+
class BackupError(Exception):
pass
+
class BackupPrereqError(Exception):
pass
-
diff --git a/xmldumps-backup/dumps/fileutils.py
b/xmldumps-backup/dumps/fileutils.py
index 0334061..22bb4ab 100644
--- a/xmldumps-backup/dumps/fileutils.py
+++ b/xmldumps-backup/dumps/fileutils.py
@@ -1,6 +1,9 @@
# Worker process, does the actual dumping
-import hashlib, os, re, sys
+import hashlib
+import os
+import re
+import sys
import time
import signal
import traceback
@@ -130,7 +133,7 @@
(file_base, self.file_type) = file_base.split('.', 1)
# some files are not of this form, we skip them
- if not '-' in file_base:
+ if '-' not in file_base:
return False
(self.db_name, self.date, self.dumpname) = file_base.split('-', 2)
@@ -187,7 +190,7 @@
filename = filename + "-tmp"
return filename
-#class DumpFile(file):
+
class DumpFile(object):
"""File containing output created by any job of a jump run. This includes
any file that follows the standard naming convention, i.e.
@@ -433,7 +436,6 @@
date_string = self._wiki.date
return os.path.join(self._wiki.webDir(), date_string,
dump_file.filename)
-
def web_path_relative(self, dump_file, date_string=None):
"""Given a DumpFilename object produce the url relative
to the docroot for the filename for the date of
@@ -448,7 +450,7 @@
directory = os.path.join(self._wiki.publicDir(), date)
if exists(directory):
dir_time_stamp = os.stat(directory).st_mtime
- if not date in self._dir_cache or dir_time_stamp >
self._dir_cache_time[date]:
+ if date not in self._dir_cache or dir_time_stamp >
self._dir_cache_time[date]:
return True
else:
return False
@@ -512,20 +514,20 @@
if dump_name and fobj.dumpname != dump_name:
continue
- if file_type != None and fobj.file_type != file_type:
+ if file_type is not None and fobj.file_type != file_type:
continue
- if file_ext != None and fobj.file_ext != file_ext:
+ if file_ext is not None and fobj.file_ext != file_ext:
continue
- if chunks == False and fobj.is_chunk_file:
+ if chunks is False and fobj.is_chunk_file:
continue
- if chunks == True and not fobj.is_chunk_file:
+ if chunks is True and not fobj.is_chunk_file:
continue
# chunks is a list...
- if chunks and chunks != True and not fobj.chunk_int in chunks:
+ if chunks and chunks is not True and fobj.chunk_int not in chunks:
continue
- if (temp == False and fobj.is_temp_file) or (temp and not
fobj.is_temp_file):
+ if (temp is False and fobj.is_temp_file) or (temp and not
fobj.is_temp_file):
continue
- if ((checkpoint == False and fobj.is_checkpoint_file) or
+ if ((checkpoint is False and fobj.is_checkpoint_file) or
(checkpoint and not fobj.is_checkpoint_file)):
continue
files_matched.append(fobj)
@@ -567,4 +569,3 @@
'''
return self._get_files_filtered(date, dump_name, file_type,
file_ext, chunks, temp,
checkpoint=False)
-
diff --git a/xmldumps-backup/dumps/jobs.py b/xmldumps-backup/dumps/jobs.py
index f19a7fe..0289a3c 100644
--- a/xmldumps-backup/dumps/jobs.py
+++ b/xmldumps-backup/dumps/jobs.py
@@ -4,7 +4,10 @@
to recombining multiple stub dumps into one file
'''
-import os, re, sys, time
+import os
+import re
+import sys
+import time
import signal
import traceback
@@ -15,6 +18,7 @@
from dumps.exceptions import *
from dumps.fileutils import *
from dumps.utils import MultiVersion, RunInfo
+
class Dump(object):
def __init__(self, name, desc, verbose=False):
@@ -239,7 +243,7 @@
for file_obj in files:
# uh oh FIXME
-# f = MiscUtils.shellEscape(file_obj.filename)
+ # f = MiscUtils.shellEscape(file_obj.filename)
fpath = runner.dump_dir.filename_public_path(file_obj)
chunknum = chunknum + 1
pipeline = []
@@ -369,7 +373,6 @@
None, dname, self.file_type, self.file_ext, chunks, temp=True))
return files
-
# unused
# list noncheckpoint chunk files that have been produced
def list_reg_files_chunked_existing(self, dump_dir, runner,
dump_names=None, date=None):
@@ -432,7 +435,6 @@
None, dname, self.file_type, self.file_ext, chunks=False,
temp=True))
return files
-
# internal function which all the public get*Possible functions call
# list all files that could be created for the given dumpname, filtering
by the given args.
# by definition, checkpoint files are never returned in such a list, as we
don't
@@ -446,12 +448,12 @@
def _get_files_possible(self, dump_dir, date=None, dumpname=None,
file_type=None, file_ext=None, chunks=None,
temp=False):
files = []
- if dumpname == None:
+ if dumpname is None:
dumpname = self.dumpname
- if chunks == None or chunks == False:
+ if chunks is None or chunks is False:
files.append(DumpFilename(dump_dir._wiki, date, dumpname,
file_type, file_ext, None, None, temp))
- if chunks == True or chunks == None:
+ if chunks is True or chunks is None:
chunks = self.get_chunk_list()
if chunks:
for chunk in chunks:
@@ -503,7 +505,6 @@
files.extend(self._get_files_possible(
dump_dir, None, dname, self.file_type, self.file_ext, chunks,
temp=True))
return files
-
# unused
# based on dump name, chunks, etc. get all the
@@ -563,7 +564,7 @@
# what's being re-run.
def list_outfiles_to_publish(self, dump_dir, dump_names=None):
# some stages (eg XLMStubs) call this for several different dump_names
- if dump_names == None:
+ if dump_names is None:
dump_names = [self.dumpname]
files = []
if self.checkpoint_file is not None:
@@ -589,7 +590,7 @@
# or to the chunkless files if there are no chunks enabled.
def list_outfiles_to_check_for_truncation(self, dump_dir, dump_names=None):
# some stages (eg XLMStubs) call this for several different dump_names
- if dump_names == None:
+ if dump_names is None:
dump_names = [self.dumpname]
files = []
if self.checkpoint_file is not None:
@@ -613,7 +614,7 @@
# is being redone, or to the chunkless files if there are no chunks
enabled.
def list_outfiles_for_build_command(self, dump_dir, dump_names=None):
# some stages (eg XLMStubs) call this for several different dump_names
- if dump_names == None:
+ if dump_names is None:
dump_names = [self.dumpname]
files = []
if self.checkpoint_file is not None:
@@ -637,7 +638,7 @@
# or to the chunkless files if there are no chunks enabled.
def list_outfiles_for_cleanup(self, dump_dir, dump_names=None):
# some stages (eg XLMStubs) call this for several different dump_names
- if dump_names == None:
+ if dump_names is None:
dump_names = [self.dumpname]
files = []
if self.checkpoint_file is not None:
@@ -665,7 +666,7 @@
# and we only do it once per job so who cares.)
def list_outfiles_for_input(self, dump_dir, dump_names=None):
# some stages (eg XLMStubs) call this for several different dump_names
- if dump_names == None:
+ if dump_names is None:
dump_names = [self.dumpname]
files = []
if self._checkpoints_enabled:
@@ -675,6 +676,7 @@
files.extend(self.list_reg_files_per_chunk_existing(
dump_dir, self.get_chunk_list(), dump_names))
return files
+
class PublicTable(Dump):
"""Dump of a table using MySQL's mysqldump utility."""
@@ -719,6 +721,7 @@
commands = runner.db_server_info.build_sqldump_command(table,
runner.wiki.config.gzip)
return runner.save_command(commands, outfile)
+
class PrivateTable(PublicTable):
"""Hidden table dumps for private data."""
@@ -754,6 +757,7 @@
def list_outfiles_to_publish(self, dump_dir):
"""Private table won't have public files to list."""
return []
+
class XmlStub(Dump):
"""Create lightweight skeleton dumps, minus bulk text.
@@ -815,7 +819,7 @@
return files
def list_outfiles_for_input(self, dump_dir, dump_names=None):
- if dump_names == None:
+ if dump_names is None:
dump_names = self.list_dumpnames()
files = []
files.extend(Dump.list_outfiles_for_input(self, dump_dir, dump_names))
@@ -847,7 +851,7 @@
# whatever that is.
command.append(startopt)
if outf.chunk_int < len(self._chunks):
- end = sum([self._chunks[i] for i in range(0, outf.chunk_int)])
+1
+ end = sum([self._chunks[i] for i in range(0, outf.chunk_int)])
+ 1
endopt = "--end=%s" % end
command.append(endopt)
@@ -869,6 +873,7 @@
callback_stderr_arg=runner)
if error:
raise BackupError("error producing stub files")
+
class RecombineXmlStub(Dump):
def __init__(self, name, desc, item_for_xml_stubs):
@@ -935,6 +940,7 @@
if error:
raise BackupError("error recombining stub files")
+
class XmlLogging(Dump):
""" Create a logging dump of all page activity """
@@ -978,6 +984,7 @@
callback_stderr_arg=runner)
if error:
raise BackupError("error dumping log files")
+
class XmlDump(Dump):
"""Primary XML dumps, one section at a time."""
@@ -1051,8 +1058,8 @@
commands.append(series)
else:
for inp_file in input_files:
-# output_file = DumpFilename(self.wiki, inp_file.date,
inp_file.dumpname,
-# inp_file.file_type, self.file_ext)
+ # output_file = DumpFilename(self.wiki, inp_file.date,
inp_file.dumpname,
+ # inp_file.file_type, self.file_ext)
series = self.build_command(runner, inp_file)
commands.append(series)
@@ -1183,7 +1190,7 @@
stub_option = "--stub=gzip:%s" %
runner.dump_dir.filename_public_path(outfile)
# Try to pull text from the previous run; most stuff hasn't changed
- #Source=$OutputDir/pages_$section.xml.bz2
+ # Source=$OutputDir/pages_$section.xml.bz2
sources = []
possible_sources = None
if self._prefetch:
@@ -1267,18 +1274,18 @@
file_obj, self.verbose)
file_obj.first_page_id = fname.find_first_page_id_in_file()
- # get the files that cover our range
+ # get the files that cover our range
for file_obj in file_list:
- # If some of the file_objs in file_list could not be properly
be parsed, some of
- # the (int) conversions below will fail. However, it is of
little use to us,
- # which conversion failed. /If any/ conversion fails, it
means, that that we do
- # not understand how to make sense of the current file_obj.
Hence we cannot use
- # it as prefetch object and we have to drop it, to avoid
passing a useless file
- # to the text pass. (This could days as of a comment below,
but by not passing
- # a likely useless file, we have to fetch more texts from the
database)
- #
- # Therefore try...except-ing the whole block is sufficient: If
whatever error
- # occurs, we do not abort, but skip the file for prefetch.
+ # If some of the file_objs in file_list could not be
properly be parsed, some of
+ # the (int) conversions below will fail. However, it is of
little use to us,
+ # which conversion failed. /If any/ conversion fails, it
means, that that we do
+ # not understand how to make sense of the current
file_obj. Hence we cannot use
+ # it as prefetch object and we have to drop it, to avoid
passing a useless file
+ # to the text pass. (This could days as of a comment
below, but by not passing
+ # a likely useless file, we have to fetch more texts from
the database)
+ #
+ # Therefore try...except-ing the whole block is
sufficient: If whatever error
+ # occurs, we do not abort, but skip the file for prefetch.
try:
# If we could properly parse
first_page_id_in_file = int(file_obj.first_page_id)
@@ -1310,10 +1317,10 @@
# also be sure that if a critical page is deleted
by the time we
# try to figure out ranges, that we don't get hosed
if ((first_page_id_in_file <= int(start_page_id) and
- (last_page_id_in_file == None or
- last_page_id_in_file >= int(start_page_id)))
or
+ (last_page_id_in_file is None or
+ last_page_id_in_file >= int(start_page_id)))
or
(first_page_id_in_file >= int(start_page_id)
and
- (end_page_id == None or
+ (end_page_id is None or
first_page_id_in_file <= int(end_page_id)))):
possibles.append(file_obj)
except:
@@ -1368,7 +1375,7 @@
if len(possible_prefetch_list):
return possible_prefetch_list
- # last shot, get output file that contains all the pages,
if there is one
+ # last shot, get output file that contains all the pages, if there
is one
files = self.list_reg_files_existing(runner.dump_dir,
[self.dumpname],
date, chunks=False)
# there is only one, don't bother to check for relevance :-P
@@ -1413,6 +1420,7 @@
else:
files_to_return.append(fname)
return files_to_return
+
class RecombineXmlDump(XmlDump):
def __init__(self, name, desc, detail, item_for_xml_dumps):
@@ -1461,6 +1469,7 @@
if error:
raise BackupError("error recombining xml bz2 files")
+
class XmlMultiStreamDump(XmlDump):
"""Take a .bz2 and recompress it as multistream bz2, 100 pages per
stream."""
@@ -1541,7 +1550,7 @@
outfile_index = runner.dump_dir.filename_public_path(
self.get_multistream_index_fname(fname))
infile = runner.dump_dir.filename_public_path(input_file)
- command_pipe = [["%s -dc %s | %s --pagesperstream 100 --buildindex
%s > %s" %
+ command_pipe = [["%s -dc %s | %s --pagesperstream 100 --buildindex
%s > %s" %
(self.wiki.config.bzip2, infile,
self.wiki.config.recompressxml,
outfile_index, outfile)]]
command_series.append(command_pipe)
@@ -1617,7 +1626,7 @@
# does just the chunks we do if there is a limit
def list_outfiles_for_cleanup(self, dump_dir, dump_names=None):
# some stages (eg XLMStubs) call this for several different dump_names
- if dump_names == None:
+ if dump_names is None:
dump_names = [self.dumpname]
multistream_names = []
for dname in dump_names:
@@ -1647,6 +1656,7 @@
files.append(self.get_multistream_index_fname(inp_file))
return files
+
class BigXmlDump(XmlDump):
"""XML page dump for something larger, where a 7-Zip compressed copy
could save 75% of download time for some users."""
@@ -1654,6 +1664,7 @@
def build_eta(self, runner):
"""Tell the dumper script whether to make ETA estimate on page or
revision count."""
return "--full"
+
class XmlRecompressDump(Dump):
"""Take a .bz2 and recompress it as 7-Zip."""
@@ -1700,7 +1711,7 @@
outfile.checkpoint)
outfilepath = runner.dump_dir.filename_public_path(outfile)
infilepath = runner.dump_dir.filename_public_path(input_file)
- command_pipe = [["%s -dc %s | %s a -mx=4 -si %s" %
+ command_pipe = [["%s -dc %s | %s a -mx=4 -si %s" %
(self.wiki.config.bzip2, infilepath,
self.wiki.config.sevenzip, outfilepath)]]
command_series.append(command_pipe)
@@ -1776,7 +1787,7 @@
# does just the chunks we do if there is a limit
def list_outfiles_for_cleanup(self, dump_dir, dump_names=None):
# some stages (eg XLMStubs) call this for several different dump_names
- if dump_names == None:
+ if dump_names is None:
dump_names = [self.dumpname]
files = []
if self.item_for_recompression._checkpoints_enabled:
@@ -1855,6 +1866,7 @@
if error:
raise BackupError("error recombining xml bz2 file(s)")
+
class AbstractDump(Dump):
"""XML dump for Yahoo!'s Active Abstracts thingy"""
@@ -1892,7 +1904,7 @@
variants.append(variant_option)
command.extend(["--outfiles=%s" % ",".join(outputs),
- "--variants=%s" % ",".join(variants)])
+ "--variants=%s" % ",".join(variants)])
if fname.chunk:
# set up start end end pageids for this piece
@@ -1903,7 +1915,7 @@
# whatever that is.
command.append(startopt)
if fname.chunk_int < len(self._chunks):
- end = sum([self._chunks[i] for i in range(0,
fname.chunk_int)]) +1
+ end = sum([self._chunks[i] for i in range(0,
fname.chunk_int)]) + 1
endopt = "--end=%s" % end
command.append(endopt)
pipeline = [command]
@@ -2033,6 +2045,7 @@
if error:
raise BackupError("error recombining abstract dump files")
+
class TitleDump(Dump):
"""This is used by "wikiproxy", a program to add Wikipedia links to BBC
news online"""
@@ -2070,6 +2083,7 @@
command = runner.db_server_info.build_sql_command(query,
runner.wiki.config.gzip)
return runner.save_command(command, outfile)
+
class AllTitleDump(TitleDump):
def get_dumpname(self):
diff --git a/xmldumps-backup/dumps/runnerutils.py
b/xmldumps-backup/dumps/runnerutils.py
index 94f379a..d59b217 100644
--- a/xmldumps-backup/dumps/runnerutils.py
+++ b/xmldumps-backup/dumps/runnerutils.py
@@ -1,5 +1,8 @@
# Worker process, does the actual dumping
-import os, re, sys, time
+import os
+import re
+import sys
+import time
import traceback
from os.path import exists
@@ -7,8 +10,10 @@
from dumps.exceptions import BackupError
from dumps.fileutils import DumpFile, DumpFilename
+
def xml_escape(text):
return text.replace("&", "&").replace("<", "<").replace(">", ">")
+
class Maintenance(object):
@@ -60,7 +65,7 @@
dumpfile = DumpFile(self.wiki,
runner.dump_dir.filename_public_path(file_obj),
None, self.verbose)
checksum = dumpfile.checksum(htype)
- if checksum != None:
+ if checksum is not None:
output.write("%s %s\n" % (checksum, file_obj.filename))
output.close()
@@ -90,6 +95,7 @@
#
# functions internal to the class
#
+
def _get_checksum_filename(self, htype):
file_obj = DumpFilename(self.wiki, None,
self.get_checksum_filename_basename(htype))
return self.dump_dir.filename_public_path(file_obj)
@@ -191,7 +197,7 @@
basename = self.checksums.get_checksum_filename_basename(htype)
path = DumpFilename(self.wiki, None, basename)
web_path = self.dump_dir.web_path_relative(path)
- return '<a href="%s">(%s)</a>' %(web_path, htype)
+ return '<a href="%s">(%s)</a>' % (web_path, htype)
def _report_dbstatus_detailed(self, done=False):
"""Put together a status page for this database, with all its
component dumps."""
@@ -287,6 +293,7 @@
html += "</li>"
return html
+
class NoticeFile(object):
def __init__(self, wiki, notice, enabled):
self.wiki = wiki
@@ -298,13 +305,13 @@
if self._enabled:
notice_file = self._get_notice_filename()
# delnotice. toss any existing file
- if self.notice == False:
+ if self.notice is False:
if exists(notice_file):
os.remove(notice_file)
self.notice = ""
# addnotice, stuff notice in a file for other jobs etc
elif self.notice != "":
-# notice_dir = self._get_notice_dir()
+ # notice_dir = self._get_notice_dir()
FileUtils.writeFile(self.wiki.config.tempDir, notice_file,
self.notice,
self.wiki.config.fileperms)
# default case. if there is a file get the contents, otherwise
@@ -320,7 +327,6 @@
self.notice = FileUtils.readFile(notice_file)
else:
self.notice = ""
-
#
# functions internal to class
@@ -424,6 +430,7 @@
self.debugfn("Removing old symlink %s -> %s" % (link,
realfile))
os.remove(link)
+
class Feeds(object):
def __init__(self, wiki, dump_dir, dbname, debugfn, enabled):
self.wiki = wiki
diff --git a/xmldumps-backup/dumps/utils.py b/xmldumps-backup/dumps/utils.py
index d085eb4..579e374 100644
--- a/xmldumps-backup/dumps/utils.py
+++ b/xmldumps-backup/dumps/utils.py
@@ -2,14 +2,19 @@
misc utils for dumps
'''
-import os, re, sys, time
-import traceback, socket
+import os
+import re
+import sys
+import time
+import traceback
+import socket
from os.path import exists
from subprocess import Popen, PIPE
from dumps.WikiDump import FileUtils, MiscUtils
from dumps.CommandManagement import CommandPipeline
from dumps.exceptions import BackupError
+
class MultiVersion(object):
def mw_script_as_string(config, maintenance_script):
@@ -36,6 +41,7 @@
mw_script_as_string = staticmethod(mw_script_as_string)
mw_script_as_array = staticmethod(mw_script_as_array)
mw_version = staticmethod(mw_version)
+
class DbServerInfo(object):
def __init__(self, wiki, db_name, error_callback=None):
@@ -75,7 +81,7 @@
match = wgdb_prefix_pattern.match(line)
if match:
self.db_table_prefix = match.group('prefix').strip()
- if self.db_table_prefix == None:
+ if self.db_table_prefix is None:
# if we didn't see this in the globals list, something is broken.
raise BackupError("Failed to get database table prefix for %s,
bailing."
% self.wiki.config.php)
@@ -87,11 +93,11 @@
# so we rewrite the localhost to it's ip address
host = socket.gethostbyname(self.db_server)
- params = ["-h", "%s" % host] # Host
+ params = ["-h", "%s" % host] # Host
if self.db_port:
- params += ["--port", "%s" % self.db_port] # Port
- params += ["-u", "%s" % self.wiki.config.dbUser] # Username
- params += ["%s" % self.password_option()] # Password
+ params += ["--port", "%s" % self.db_port] # Port
+ params += ["-u", "%s" % self.wiki.config.dbUser] # Username
+ params += ["%s" % self.password_option()] # Password
return params
def build_sql_command(self, query, pipeto=None):
@@ -138,6 +144,7 @@
else:
return "-p" + self.wiki.config.dbPassword
+
class RunSimpleCommand(object):
def run_and_return(command, log_callback=None):
"""Run a command and return the output as a string.
@@ -165,6 +172,7 @@
run_and_return = staticmethod(run_and_return)
+
class PageAndEditStats(object):
def __init__(self, wiki, db_name, error_callback=None):
self.total_pages = None
@@ -182,7 +190,7 @@
retries = 0
maxretries = 5
results = self.db_server_info.run_sql_and_get_output(query)
- while results == None and retries < maxretries:
+ while results is None and retries < maxretries:
retries = retries + 1
time.sleep(5)
results = self.db_server_info.run_sql_and_get_output(query)
@@ -196,7 +204,7 @@
retries = 0
results = None
results = self.db_server_info.run_sql_and_get_output(query)
- while results == None and retries < maxretries:
+ while results is None and retries < maxretries:
retries = retries + 1
time.sleep(5)
results = self.db_server_info.run_sql_and_get_output(query)
@@ -238,7 +246,7 @@
status = self._get_status_from_runinfo(old_dump_runinfo_filename,
job_name)
if status == "done":
return 1
- elif not status == None:
+ elif status is not None:
# failure, in progress, some other useless thing
return 0
@@ -336,7 +344,7 @@
infile = open(filename, "r")
for line in infile:
result = self._get_status_from_runinfo_line(line, job_name)
- if not result == None:
+ if result is not None:
return result
infile.close()
return None
@@ -349,7 +357,7 @@
# find desc in there, look for "class='done'"
def _get_status_from_html_line(self, line, desc):
- if not ">"+desc+"<" in line:
+ if ">"+desc+"<" not in line:
return None
if "<li class='done'>" in line:
return "done"
@@ -365,7 +373,7 @@
infile = open(filename, "r")
for line in infile:
result = self._get_status_from_html_line(line, desc)
- if not result == None:
+ if result is not None:
return result
infile.close()
return None
diff --git a/xmldumps-backup/monitor.py b/xmldumps-backup/monitor.py
index c9333d5..5c4715c 100644
--- a/xmldumps-backup/monitor.py
+++ b/xmldumps-backup/monitor.py
@@ -5,9 +5,11 @@
from os.path import exists
from dumps.WikiDump import FileUtils, Wiki, Config
+
def add_to_filename(filename, infix):
base, suffix = filename.split('.', 1)
return base + "-" + infix + ("." + suffix if suffix else "")
+
def generate_index(config, other_indexhtml=None, sorted_by_db=False,
showlocks=True):
running = False
@@ -58,6 +60,7 @@
"status": status,
"items": "\n".join(states)}
+
def update_index(config):
output_fname = os.path.join(config.publicDir, config.index)
output_fname_sorted_by_db = add_to_filename(os.path.join(
@@ -76,6 +79,7 @@
filehdl.close()
os.rename(temp_fname, output_fname_sorted_by_db)
+
def main():
# can specify name of alternate config file
if len(sys.argv) >= 2:
diff --git a/xmldumps-backup/worker.py b/xmldumps-backup/worker.py
index aea70c0..66bc60a 100644
--- a/xmldumps-backup/worker.py
+++ b/xmldumps-backup/worker.py
@@ -1,8 +1,12 @@
# Worker process, does the actual dumping
-import getopt, os, sys
+import getopt
+import os
+import sys
import shutil
-import Queue, thread, traceback
+import Queue
+import thread
+import traceback
from os.path import exists
from dumps.WikiDump import TimeUtils, Wiki, Config, cleanup
@@ -17,6 +21,7 @@
from dumps.runnerutils import Checksummer, Status, Maintenance
from dumps.utils import DbServerInfo, RunInfoFile, Chunk
+
class Logger(object):
@@ -54,6 +59,7 @@
# set in order to have logging thread clean up and exit
def indicate_jobs_done(self):
self.queue.put_nowait(self.jobs_done)
+
class DumpItemList(object):
def __init__(self, wiki, prefetch, spawn, chunk_to_do, checkpoint_file,
@@ -114,20 +120,20 @@
"Data for blocks of IP addresses,
ranges, and users."),
PrivateTable("archive", "archivetable",
"Deleted page and revision data."),
- #PrivateTable("updates", "updatestable",
+ # PrivateTable("updates", "updatestable",
# "Update dataset for OAI updater
system."),
PrivateTable("logging", "loggingtable",
"Data for various events (deletions,
uploads, etc)."),
PrivateTable("oldimage", "oldimagetable",
"Metadata on prior versions of
uploaded images."),
- #PrivateTable("filearchive", "filearchivetable",
+ # PrivateTable("filearchive", "filearchivetable",
# "Deleted image data"),
PublicTable("site_stats", "sitestatstable",
"A few statistics such as the page
count."),
PublicTable("image", "imagetable",
"Metadata on current versions of
uploaded media/files."),
- #PublicTable("oldimage", "oldimagetable",
+ # PublicTable("oldimage", "oldimagetable",
# "Metadata on prior versions of
uploaded media/files."),
PublicTable("pagelinks", "pagelinkstable",
"Wiki page-to-page link records."),
@@ -141,7 +147,7 @@
"Wiki external URL link records."),
PublicTable("langlinks", "langlinkstable",
"Wiki interlanguage link records."),
- #PublicTable("interwiki", "interwikitable",
+ # PublicTable("interwiki", "interwikitable",
# "Set of defined interwiki prefixes " +
# "and links for this wiki."),
PublicTable("user_groups", "usergroupstable", "User
group assignments."),
@@ -155,9 +161,9 @@
"Name/value pairs for pages."),
PublicTable("protected_titles",
"protectedtitlestable",
"Nonexistent pages that have been
protected."),
- #PublicTable("revision", revisiontable",
+ # PublicTable("revision", revisiontable",
# "Base per-revision data (does not
include text)."), // safe?
- #PrivateTable("text", "texttable",
+ # PrivateTable("text", "texttable",
# "Text blob storage. May be compressed,
etc."), // ?
PublicTable("redirect", "redirecttable", "Redirect
list"),
PublicTable("iwlinks", "iwlinkstable",
@@ -456,6 +462,7 @@
# even if the item has never been run we will at least have "waiting"
in the status
return "name:%s; status:%s; updated:%s" % (item.name(), item.status(),
item.updated())
+
class Runner(object):
def __init__(self, wiki, prefetch=True, spawn=True, job=None,
skip_jobs=None,
restart=False, notice="", dryrun=False, loggingEnabled=False,
@@ -707,7 +714,7 @@
print "This means that the status information about the old
run will be lost, and"
print "only the information about the current (and future)
runs will be kept."
reply = raw_input("Continue anyways? [y/N]: ")
- if not reply in ["y", "Y"]:
+ if reply not in ["y", "Y"]:
raise RuntimeError("No run information available for
previous dump, exiting")
if not self.dump_item_list.mark_dumps_to_run(self.job_requested,
self.skipdone):
@@ -913,6 +920,7 @@
self.debug("Creating %s ..." % dirname)
os.makedirs(dirname)
+
def check_jobs(wiki, date, job, skipjobs, page_id_range, chunk_to_do,
checkpoint_file, prereqs=False, restart=False):
'''
@@ -1090,6 +1098,7 @@
sys.stderr.write(usage_text)
sys.exit(1)
+
def main():
try:
date = None
@@ -1198,10 +1207,9 @@
config = Config(config_file)
else:
config = Config()
- externals = [
- 'php', 'mysql', 'mysqldump', 'head', 'tail',
- 'checkforbz2footer', 'grep', 'gzip', 'bzip2',
- 'writeuptopageid', 'recompressxml', 'sevenzip', 'cat',]
+ externals = ['php', 'mysql', 'mysqldump', 'head', 'tail',
+ 'checkforbz2footer', 'grep', 'gzip', 'bzip2',
+ 'writeuptopageid', 'recompressxml', 'sevenzip', 'cat']
failed = False
unknowns = []
@@ -1224,7 +1232,7 @@
sys.stderr.write("Exiting.\n")
sys.exit(1)
- if dryrun or chunk_to_do or (job_requested and not restart and not
do_locking):
+ if dryrun or chunk_to_do or (job_requested and not restart and not
do_locking):
locks_enabled = False
else:
locks_enabled = True
@@ -1296,7 +1304,7 @@
checkpoint_file = None
after_checkpoint_jobs = ['articlesdump', 'metacurrentdump',
'metahistorybz2dump']
- if not job_requested or not job_requested in [
+ if not job_requested or job_requested not in [
'articlesdump', 'metacurrentdump',
'metahistorybz2dump']:
usage("--aftercheckpoint option requires --job option with
one of %s"
% ", ".join(after_checkpoint_jobs))
diff --git a/xmldumps-backup/xmlabstracts.py b/xmldumps-backup/xmlabstracts.py
index aa5fba6..478a4d6 100644
--- a/xmldumps-backup/xmlabstracts.py
+++ b/xmldumps-backup/xmlabstracts.py
@@ -9,7 +9,6 @@
import os
import sys
-import worker
from dumps.WikiDump import Config
from dumps.utils import MultiVersion
import getopt
@@ -54,10 +53,9 @@
for filetype in outfiles:
command.extend(["--output=file:%s" % outfiles[filetype]['temp'],
- "--filter=namespace:NS_MAIN",
- "----filter=noredirect",
- "--filter=abstract%s" % filetype
- ])
+ "--filter=namespace:NS_MAIN",
+ "----filter=noredirect",
+ "--filter=abstract%s" % filetype])
do_xml_stream(wikidb, outfiles, command, wikiconf,
start, end, dryrun, 'page_id', 'page',
diff --git a/xmldumps-backup/xmllogs.py b/xmldumps-backup/xmllogs.py
index 5cd6965..bccfa50 100644
--- a/xmldumps-backup/xmllogs.py
+++ b/xmldumps-backup/xmllogs.py
@@ -9,12 +9,10 @@
import os
import sys
-import time
-import worker
from dumps.WikiDump import Config
from dumps.utils import MultiVersion
import getopt
-from xmlstreams import run_script, catfile, gzippit, get_max_id, do_xml_piece,
do_xml_stream
+from xmlstreams import gzippit, do_xml_stream
def dologsbackup(wikidb, outfile,
diff --git a/xmldumps-backup/xmlstreams.py b/xmldumps-backup/xmlstreams.py
index 7840d32..d0fb8dc 100644
--- a/xmldumps-backup/xmlstreams.py
+++ b/xmldumps-backup/xmlstreams.py
@@ -12,12 +12,12 @@
import time
import worker
from dumps.WikiDump import Wiki
-import getopt
from subprocess import Popen, PIPE
# fix all the error returns and make subroutines out of stuff
# current code puts together a command with a bunch of crap in it
+
def do_xml_stream(wikidb, outfiles, command, wikiconf,
start, end, dryrun, id_field, table,
@@ -160,7 +160,7 @@
lines = results.splitlines()
if lines and lines[1]:
if not lines[1].isdigit():
- return 0 #probably NULL or missing table
+ return 0 # probably NULL or missing table
end = int(lines[1])
return end
diff --git a/xmldumps-backup/xmlstubs.py b/xmldumps-backup/xmlstubs.py
index b705665..31a1bb4 100644
--- a/xmldumps-backup/xmlstubs.py
+++ b/xmldumps-backup/xmlstubs.py
@@ -9,12 +9,10 @@
import os
import sys
-import time
-import worker
from dumps.WikiDump import Config
from dumps.utils import MultiVersion
import getopt
-from xmlstreams import run_script, catfile, gzippit, get_max_id, do_xml_piece,
do_xml_stream
+from xmlstreams import gzippit, do_xml_stream
def dostubsbackup(wikidb, history_file, current_file, articles_file,
@@ -28,7 +26,8 @@
'current': {'name': current_file},
'articles': {'name': articles_file}}
for filetype in outfiles:
- outfiles[filetype]['temp'] = os.path.join(wikiconf.tempDir,
os.path.basename(outfiles[filetype]['name']) + "_tmp")
+ outfiles[filetype]['temp'] = os.path.join(
+ wikiconf.tempDir, os.path.basename(outfiles[filetype]['name']) +
"_tmp")
if dryrun:
outfiles[filetype]['compr'] = None
else:
--
To view, visit https://gerrit.wikimedia.org/r/243374
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ib0063be4981a2b34a99375e9dc08bff8a46ec45f
Gerrit-PatchSet: 1
Gerrit-Project: operations/dumps
Gerrit-Branch: ariel
Gerrit-Owner: ArielGlenn <[email protected]>
Gerrit-Reviewer: ArielGlenn <[email protected]>
Gerrit-Reviewer: jenkins-bot <>
_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits