/
carbon-cache.py
executable file
·215 lines (163 loc) · 6.19 KB
/
carbon-cache.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
#!/usr/bin/env python
"""Copyright 2009 Chris Davis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License."""
import sys
import os
import socket
import pwd
import optparse
import atexit
from os.path import basename, dirname, exists, join, isdir
program = basename( sys.argv[0] )
hostname = socket.gethostname().split('.')[0]
os.umask(022)
# Initialize twisted
try:
from twisted.internet import epollreactor
epollreactor.install()
except:
pass
from twisted.internet import reactor
# Figure out where we're installed
BIN_DIR = dirname( os.path.abspath(__file__) )
ROOT_DIR = dirname(BIN_DIR)
STORAGE_DIR = join(ROOT_DIR, 'storage')
LOG_DIR = join(STORAGE_DIR, 'log', 'carbon-cache')
LIB_DIR = join(ROOT_DIR, 'lib')
CONF_DIR = join(ROOT_DIR, 'conf')
__builtins__.CONF_DIR = CONF_DIR # evil I know, but effective.
sys.path.insert(0, LIB_DIR)
# Capture useful debug info for this commonly reported problem
try:
import carbon
except ImportError:
print 'Failed to import carbon, debug information follows.'
print 'pwd=%s' % os.getcwd()
print 'sys.path=%s' % sys.path
print '__file__=%s' % __file__
sys.exit(1)
# Import application components
from carbon.conf import settings
from carbon.log import logToStdout, logToDir
from carbon.listeners import MetricLineReceiver, MetricPickleReceiver, CacheQueryHandler, startListener
from carbon.cache import MetricCache
from carbon.instrumentation import startRecordingCacheMetrics
from carbon.events import metricReceived
# Parse command line options
parser = optparse.OptionParser(usage='%prog [options] <start|stop|status>')
parser.add_option('--debug', action='store_true', help='Run in the foreground, log to stdout')
parser.add_option('--profile', help='Record performance profile data to the given file')
parser.add_option('--pidfile', default=join(STORAGE_DIR, '%s.pid' % program.split('.')[0]), help='Write pid to the given file')
parser.add_option('--config', default=join(CONF_DIR, 'carbon.conf'), help='Use the given config file')
parser.add_option('--logdir', default=LOG_DIR, help="Write logs in the given directory")
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
raise SystemExit(1)
action = args[0]
if action == 'stop':
if not exists(options.pidfile):
print 'Pidfile %s does not exist' % options.pidfile
raise SystemExit(0)
pidfile = open(options.pidfile, 'r')
try:
pid = int( pidfile.read().strip() )
except:
print 'Could not read pidfile %s' % options.pidfile
raise SystemExit(1)
print 'Deleting %s (contained pid %d)' % (options.pidfile, pid)
os.unlink(options.pidfile)
print 'Sending kill signal to pid %d' % pid
os.kill(pid, 15)
raise SystemExit(0)
elif action == 'status':
if not exists(options.pidfile):
print '%s is not running' % program
raise SystemExit(0)
pidfile = open(options.pidfile, 'r')
try:
pid = int( pidfile.read().strip() )
except:
print 'Failed to read pid from %s' % options.pidfile
raise SystemExit(1)
if exists('/proc/%d' % pid):
print "%s is running with pid %d" % (program, pid)
raise SystemExit(0)
else:
print "%s is not running" % program
raise SystemExit(0)
elif action != 'start':
parser.print_usage()
raise SystemExit(1)
if exists(options.pidfile):
print "Pidfile %s already exists, is %s already running?" % (options.pidfile, program)
raise SystemExit(1)
# Read config (we want failures to occur before daemonizing)
settings.readFrom(options.config, 'cache')
storage_schemas = join(CONF_DIR, 'storage-schemas.conf')
if not exists(storage_schemas):
print "Error: missing required config %s" % storage_schemas
sys.exit(1)
use_amqp = settings.get("ENABLE_AMQP", False)
if use_amqp:
from carbon import amqp_listener
amqp_host = settings.get("AMQP_HOST", "localhost")
amqp_port = settings.get("AMQP_PORT", 5672)
amqp_user = settings.get("AMQP_USER", "guest")
amqp_password = settings.get("AMQP_PASSWORD", "guest")
amqp_verbose = settings.get("AMQP_VERBOSE", False)
amqp_vhost = settings.get("AMQP_VHOST", "/")
amqp_spec = settings.get("AMQP_SPEC", None)
amqp_exchange_name = settings.get("AMQP_EXCHANGE", "graphite")
# --debug
if options.debug:
logToStdout()
else:
if not isdir(options.logdir):
os.makedirs(options.logdir)
if settings.USER:
print "Dropping privileges to become the user %s" % settings.USER
from carbon.util import daemonize, dropprivs
daemonize()
pidfile = open(options.pidfile, 'w')
pidfile.write( str(os.getpid()) )
pidfile.close()
def shutdown():
if os.path.exists(options.pidfile):
os.unlink(options.pidfile)
atexit.register(shutdown)
if settings.USER:
pwent = pwd.getpwnam(settings.USER)
os.chown(options.pidfile, pwent.pw_uid, pwent.pw_gid)
dropprivs(settings.USER)
logToDir(options.logdir)
# Configure application components
metricReceived.installHandler(MetricCache.store)
startListener(settings.LINE_RECEIVER_INTERFACE, settings.LINE_RECEIVER_PORT, MetricLineReceiver)
startListener(settings.PICKLE_RECEIVER_INTERFACE, settings.PICKLE_RECEIVER_PORT, MetricPickleReceiver)
startListener(settings.CACHE_QUERY_INTERFACE, settings.CACHE_QUERY_PORT, CacheQueryHandler)
if use_amqp:
amqp_listener.startReceiver(amqp_host, amqp_port, amqp_user, amqp_password,
vhost=amqp_vhost, spec=amqp_spec,
exchange_name=amqp_exchange_name,
verbose=amqp_verbose)
from carbon.writer import startWriter # have to import this *after* settings are defined
startWriter()
startRecordingCacheMetrics()
# Run the twisted reactor
print "%s running" % program
if options.profile:
import cProfile
if exists(options.profile):
os.unlink(options.profile)
cProfile.run('reactor.run()', options.profile)
else:
reactor.run()