-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdfbrew.py
executable file
·302 lines (246 loc) · 10.3 KB
/
pdfbrew.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env python
import logging
import argparse
import sys
import Queue
import threading
from subprocess import Popen, PIPE
import os
import uuid
import shutil
import time
import yaml
import magic
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
class ErrorCounter:
def __init__(self):
self.tracker = {}
def get_error(self, filename):
if filename in self.tracker:
logging.debug('got error '+ filename + " tries " + str(self.tracker[filename]))
return self.tracker[filename]
else:
return None
def set_error(self, filename):
if filename in self.tracker:
self.tracker[filename] += 1
logging.debug('set error'+ filename + " tries " + str(self.tracker[filename]))
else:
self.tracker[filename] = 1
logging.debug('set error '+ filename + " tries " + str(self.tracker[filename]))
def delete_error(self, filename):
if filename in self.tracker:
del self.tracker[filename]
logging.debug('delete error for '+ filename )
def main():
"""main"""
parser = argparse.ArgumentParser(
description='Monitor folder for ps files and convert them to pdf')
parser.add_argument('-l', '--loglevel',
help='CRITICAL, ERROR, WARNING, INFO, DEBUG')
parser.add_argument('-o', '--logfile',
help='Logfile to store messages (Default: pdfbrew.log)')
parser.add_argument('-c', '--configfile', default='pdfbrew.yaml',
help='Config file yaml format')
parser.add_argument('-q', '--quiet', action='store_true',
help='Do not print logging to stdout')
args = parser.parse_args()
newconf = parse_config(args.configfile)
config = {'polling_interval' : 15, 'purge_age' : 1209600, 'purge_int' : '5 0 * * *',
'purge_err_int': 120, 'num_workers' : 4, 'delete_onfail': True,
'filetypes' : ['application/postscript', 'application/pdf',
'text/plain', 'application/octet-stream'],
'copy_original': True, 'loglevel': 'INFO',
'logfile': 'pdfbrew.log', 'fail_tries': 10}
config.update(newconf)
config['err'] = ErrorCounter()
if args.logfile:
config['logfile'] = args.logfile
if args.loglevel:
config['loglevel'] = args.loglevel
logging.basicConfig(
level=config['loglevel'],
#format='%(asctime)s %(name)-12s %(funcName)20s() %(levelname)-8s %(message)s',
format="%(levelname) -10s %(asctime)s %(module)s:%(lineno)s %(funcName)s %(message)s",
datefmt='%m-%d %H:%M',
filename=config['logfile'],
filemode='a')
pdfbrew = logging.getLogger()
if args.quiet is False:
console = logging.StreamHandler()
console.setLevel(config['loglevel'])
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
console.setFormatter(formatter)
pdfbrew.addHandler(console)
queue = Queue.Queue()
num_workers = config['num_workers']
pool = [threading.Thread(target=process_queue,
args=(queue, config)) for _ in range(num_workers)]
for worker in pool:
worker.daemon = True
worker.start()
scheduler = BackgroundScheduler(daemon=True)
scheduler.start()
scheduler.add_job(purge_old_files, CronTrigger.from_crontab(config['purge_int']), args=[queue, config])
scheduler.add_job(purge_old_errors, 'interval', seconds=int(config['purge_err_int']),
args=[queue, config])
scheduler.add_job(poll_folders, 'interval', seconds=int(config['polling_interval']),
args=[queue, config])
try:
while 1:
time.sleep(1)
except KeyboardInterrupt:
sys.exit(0)
def poll_folders(queue, config):
""" poll watched folders and put files in the process queue"""
for indir in config['watch']:
logging.debug('scaning '+ indir + ' for new files')
paths = [os.path.join(indir, fn) for fn in next(os.walk(indir))[2]]
logging.debug(indir + ' contains ' + str(len(paths)) + ' file(s)')
for path in paths:
queue.put([path, 'convert'])
logging.debug("added " + path + " to the queue")
def process_queue(queue, config):
""" process event queue """
while True:
filename, action = queue.get()
if action == 'convert':
path = os.path.dirname(filename)
convert_file(filename, config['watch'][path], config)
if action == 'delete':
delete_file(filename)
time.sleep(1)
def ps2pdf(src, dst, ps2pdf_args):
"""spawns ps2pdf process"""
name, ext = os.path.splitext(src)
out_file = dst + '/~' + os.path.basename(name) + '.tmp'
cmd = ["ps2pdf"]
if ps2pdf_args:
# replace string RANDOMPASS with random password
ps2pdf_args = ps2pdf_args.replace(
"RANDOMPASS", str(uuid.uuid4().get_hex().upper()[0:12]))
cmd = cmd + ps2pdf_args.split(' ')
proc = Popen(cmd + [src, out_file], stderr=PIPE, stdout=PIPE)
logging.debug("executing " + " ".join(str(x)
for x in cmd) + ' ' + src + ' ' + out_file)
(stdout, stderr) = proc.communicate()
if proc.returncode:
logging.debug("cannot convert file: " + src)
logging.debug(stderr)
#cleanup broken file from output if convertion failed
if os.path.exists(out_file):
delete_file(out_file)
return {'success' : False, 'error': stderr}
else:
logging.info('created temporary file ' + src + ' to ' + out_file)
return {'success' : True, 'error': None}
def convert_file(fname, outdir, config):
"""validate files and start conversion"""
if os.path.exists(fname) is False:
return
name, ext = os.path.splitext(fname)
out_file = outdir + '/~' + os.path.basename(name) + '.tmp'
final_file = outdir + '/' + os.path.basename(name) + '.pdf'
err = config['err']
tries = 0
if os.path.exists(out_file):
return
if err.get_error(final_file):
tries = err.get_error(final_file)
logging.debug('Previous error detected for ' + fname
+ ' try ' + str(tries)
+ '/' + str(config['fail_tries']))
if tries > config['fail_tries']:
logging.error('Exceeding number of attempts to convert '
+ fname)
if config['delete_onfail']:
delete_file(fname)
err.delete_error(final_file)
return
with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m:
ftype = m.id_filename(fname)
logging.debug("filename: " + fname + " is type " + ftype)
ret = {'success' : False, 'error': None}
if ftype is not False and ftype in config['filetypes']:
ret = ps2pdf(fname, outdir, config['ps2pdf_opts'])
if ret['success'] and config['copy_original']:
logging.info("Copy original file " + fname +
" to destination " + outdir)
shutil.copy2(fname, outdir)
if ret['success'] is False:
err.set_error(final_file)
else:
# if we can't remove the original than is probably locked
# and some other process is actively writing to it
delret = delete_file(fname)
if delret['success']:
rename_file(out_file, final_file)
err.delete_error(final_file)
else:
delete_file(out_file)
err.delete_error(final_file)
def parse_config(configfile):
"""parse configuration yaml file"""
cnf = open(configfile, 'r')
txt = cnf.read()
return yaml.load(txt)
def delete_file(filename):
"""delete file and catch any exceptions while doing it"""
try:
if os.path.exists(filename):
os.remove(filename)
logging.debug("Deleting " + filename)
return {'success': True}
except Exception as e:
logging.error("Cannot delete file "+ filename)
logging.exception(e)
return {'success' : False}
def rename_file(src, dest):
"""delete file and catch any exceptions while doing it"""
try:
if os.path.exists(src):
shutil.move(src, dest)
logging.info("moved tmp file " + src + " to " + dest)
return {'success': True}
except Exception as e:
logging.error("Cannot rename file "+ src + " to "+ dest)
logging.exception(e)
return {'success' : False}
def purge_old_files(queue, config):
"""purge old files after predefined period"""
logging.debug('Purging old files')
now = time.time()
i = 0
for indir in config['watch']:
logging.debug('scaning '+ indir + ' for outdated files')
paths = [os.path.join(config['watch'][indir], fn)
for fn in next(os.walk(config['watch'][indir]))[2]]
for filename in paths:
creation_time = os.path.getctime(filename) + int(config['purge_age'])
if now > creation_time:
queue.put([filename, 'delete'])
i += 1
logging.info('Purging ' + str(i) + " old files in " + config['watch'][indir])
def purge_old_errors(queue, config):
"""purge stale errors and tempfiles"""
logging.debug('Purging stale errors and tempfiles')
err = config['err']
i = 0
for indir in config['watch']:
logging.debug('scaning '+ config['watch'][indir] + ' for stale error/temporary files')
paths = [os.path.join(config['watch'][indir], fn)
for fn in next(os.walk(config['watch'][indir]))[2]]
for filename in paths:
dst = os.path.dirname(filename)
name, ext = os.path.splitext(filename)
tmp_file = dst + '/~' + os.path.basename(name) + '.TMP'
if os.path.exists(filename) and err.get_error(filename):
err.delete_error(filename)
if os.path.exists(tmp_file) and os.path.exists(filename):
queue.put([tmp_file, 'delete'])
i += 1
logging.info('Purging '+ str(i) + ' stale errors/temporary files' )
if __name__ == "__main__":
main()