-
Notifications
You must be signed in to change notification settings - Fork 1
/
response-cleanup
executable file
·207 lines (173 loc) · 7.09 KB
/
response-cleanup
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Response Project - Cleanup'''
# Copyright (C) 2009-2010 John Feuerstein <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
from globals import __author__, __copyright__, __license__, __version__
import os
import signal
import sys
import logger
import exception
from datetime import datetime, timedelta
from config import Config
from pidfile import PidFile
from optparse import OptionParser
# Option parsing
version = '%prog version ' + __version__
usage = 'Usage: %prog [options]'
parser = OptionParser(usage=usage, version=version)
# Cleanup operations (all uppercase)
parser.add_option('-A', '--all', action='store_true', dest='all_at_once',
help='perform all of the following cleanup operations in one go',)
parser.add_option('-D', '--disable-expired-configs', action='store_true',
dest='disable_expired_configs',
help='disable all response configs that have expired',)
parser.add_option('-O', '--delete-old-response-records', action='store_true',
dest='delete_old_response_records',
help='delete old response records that were not hit for a long time',)
parser.add_option('-U', '--delete-unused-response-records',
action='store_true',
dest='delete_records_of_disabled_configs',
help='delete all response records that belong to disabled configs',)
parser.add_option('-n', '--dry-run', action='store_true', dest='dryrun',
help='do not execute any query, show what would have been done',)
parser.add_option('-d', '--debug', action='store_true', dest='debug',
help='debug mode')
parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
help='verbose mode')
parser.add_option('-q', '--quiet', action='store_true', dest='quiet',
help='only log errors')
parser.add_option('-s', '--syslog', action='store_true', dest='syslog',
help='log to syslog')
parser.add_option('--syslog-facility', type='string', action='store',
dest='syslog_facility', default='MAIL',
help='specify the syslog facility (default: MAIL)')
parser.add_option('-c', '--config', action='store', dest='config_file',
help='specify an alternate path to the config file, ' \
'default: /etc/response.cfg',
default='/etc/response.cfg')
parser.add_option('-p', '--pid-file', action='store', dest='pid_file',
help='specify an alternate path to the pid file, ' \
'default: /var/run/response/cleanup.pid',
default='/var/run/response/cleanup.pid')
(options, args) = parser.parse_args()
if options.all_at_once:
options.disable_expired_configs = True
options.delete_old_response_records = True
options.delete_records_of_disabled_configs = True
if not (options.disable_expired_configs
or options.delete_old_response_records
or options.delete_records_of_disabled_configs):
print('Error: Need at least one cleanup operation!\n')
parser.print_help()
sys.exit(1)
# Logging
log = logger.getLog(
debug=options.debug,
verbose=options.verbose,
quiet=options.quiet,
syslog=options.syslog,
syslog_facility=options.syslog_facility,
)
# Signal handling
def signal_handler(signum, frame):
if signum == signal.SIGINT:
log.warning('Received SIGINT, exiting...')
raise exception.SignalReceived(signum, 'SIGINT')
elif signum == signal.SIGTERM:
log.warning('Received SIGTERM, exiting...')
raise exception.SignalReceived(signum, 'SIGTERM')
else:
log.warning('Received signal number %d, exiting...' % signum)
raise exception.SignalReceived(signum)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Main
log.warning('%s starting up... (loglevel: %s)'
% (parser.get_version(), logger.getLogLevelName(log)))
try:
pid = PidFile(file=options.pid_file)
pid.write()
except exception.PidFileError, e:
if e.stalefile:
log.fatal('Stale pidfile %s present.' % options.pid_file)
log.fatal('Response-Cleanup already running?')
else:
log.fatal('Unable to write to pidfile %s' % options.pid_file)
log.fatal('Exiting with errors...')
sys.exit(1)
log.warning('Running with PID=%d' % pid.pid)
config = Config(options.config_file)
backend = config.backend.adapter(config.backend)
ret = 0
if options.dryrun:
log.warning('DRY-RUN requested: Not performing any SQL queries!')
try:
log.warning('Initializing...')
try:
log.warning('Connecting to backend...')
connection = backend.connect()
cursor = backend.open_cursor(connection)
except Exception, e:
log.error('Error initialising backend: %s' % e)
ret = 2
raise
try:
log.warning('Executing cleanup operations')
if options.disable_expired_configs:
log.warning('Disabling expired configs')
date = datetime.now()
if not options.dryrun:
backend.disable_expired_configs(cursor, date)
backend.commit(connection)
log.warning('Success!')
if options.delete_old_response_records:
log.warning('Deleting old response records')
date = datetime.now() - timedelta(
seconds=config.cleanup.timedelta)
log.debug('Matching records with inactivity since %s' % date)
if not options.dryrun:
backend.delete_old_response_records(cursor, date)
backend.commit(connection)
log.warning('Success!')
if options.delete_records_of_disabled_configs:
log.warning('Deleting response records of disabled configs')
if not options.dryrun:
backend.delete_records_of_disabled_configs(cursor)
backend.commit(connection)
log.warning('Success!')
except exception.SignalReceived, s:
log.info('Cleanup operation received signal %d (%s)' %
(s.signum, s.signame))
ret = 3
# This may be useful someday...
except Exception, e:
ret = 1
log.error('Unhandled exception: %s' % e)
finally:
log.warning('Doing a graceful shutdown...')
backend.close_cursor(cursor)
backend.disconnect(connection)
backend.close()
except Exception, e:
ret = 1
log.error('Catched unhandled exception: %s' % e)
finally:
log.debug('Cleaning up...')
pid.delete()
log.warning('Quit.')
sys.exit(ret)