]>
git.ipfire.org Git - collecty.git/blob - src/collecty/daemon.py
2 ###############################################################################
4 # collecty - A system statistics collection daemon for IPFire #
5 # Copyright (C) 2012 IPFire development team #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
20 ###############################################################################
24 import multiprocessing
33 from constants
import *
37 log
= logging
.getLogger("collecty")
39 class Collecty(object):
40 # The default interval, when all data is written to disk.
45 def __init__(self
, debug
=False):
48 # Enable debug logging when running in debug mode
50 log
.setLevel(logging
.DEBUG
)
54 # Indicates whether this process should be running or not.
57 # The write queue holds all collected pieces of data which
58 # will be written to disk later.
59 self
.write_queue
= WriteQueue(self
, self
.SUBMIT_INTERVAL
)
61 # Create worker threads
62 self
.worker_threads
= self
.create_worker_threads()
64 self
._timer
_queue
= queue
.PriorityQueue()
65 self
._worker
_queue
= queue
.Queue()
67 # Create a thread that connects to dbus and processes requests we
69 self
.bus
= bus
.Bus(self
)
72 for plugin
in plugins
.get():
73 self
.add_plugin(plugin
)
75 log
.debug(_("Collecty successfully initialized with %s plugins") \
78 def add_plugin(self
, plugin_class
):
79 # Try initialising a new plugin. If that fails, we will log the
80 # error and try to go on.
82 plugin
= plugin_class(self
)
84 log
.critical(_("Plugin %s could not be initialised") % plugin_class
, exc_info
=True)
87 self
.plugins
.append(plugin
)
91 for plugin
in self
.plugins
:
92 for template
in plugin
.templates
:
96 # Register signal handlers.
97 self
.register_signal_handler()
102 # Initialise the timer queue
103 self
.initialise_timer_queue()
105 # Start worker threads
106 for w
in self
.worker_threads
:
109 # Run the write queue thread
110 self
.write_queue
.start()
112 # Regularly submit all data to disk.
115 # Try processing one event from the queue. If that succeeded
116 # we will retry immediately.
117 if self
.process_timer_queue():
120 # Otherwise we will sleep for a bit
121 time
.sleep(self
.HEARTBEAT
)
123 # Log warnings if the worker queue is filling up
124 queue_size
= self
._worker
_queue
.qsize()
126 log
.warning(_("Worker queue is filling up with %s events") % queue_size
)
128 except KeyboardInterrupt:
132 # Wait until all worker threads are finished
133 for w
in self
.worker_threads
:
136 # Stop the bus thread
139 # Write all collected data to disk before ending the main thread
140 self
.write_queue
.shutdown()
142 log
.debug(_("Main thread exited"))
148 log
.info(_("Received shutdown signal"))
151 # Propagating shutdown to all threads.
152 for w
in self
.worker_threads
:
155 def register_signal_handler(self
):
156 for s
in (signal
.SIGTERM
, signal
.SIGINT
, signal
.SIGUSR1
):
157 log
.debug(_("Registering signal %d") % s
)
159 signal
.signal(s
, self
.signal_handler
)
161 def signal_handler(self
, sig
, *args
, **kwargs
):
162 log
.info(_("Caught signal %d") % sig
)
164 if sig
in (signal
.SIGTERM
, signal
.SIGINT
):
165 # Shutdown this application.
168 elif sig
== signal
.SIGUSR1
:
170 self
.write_queue
.commit()
172 def get_plugin_from_template(self
, template_name
):
173 for plugin
in self
.plugins
:
174 if not template_name
in [t
.name
for t
in plugin
.templates
]:
179 def generate_graph(self
, template_name
, *args
, **kwargs
):
180 plugin
= self
.get_plugin_from_template(template_name
)
182 raise RuntimeError("Could not find template %s" % template_name
)
184 return plugin
.generate_graph(template_name
, *args
, **kwargs
)
186 def create_worker_threads(self
, num
=None):
188 Creates a number of worker threads
190 # If no number of threads is given, we will create as many as we have
191 # active processor cores but never less than four.
193 num
= max(multiprocessing
.cpu_count(), 4)
197 for id in range(num
):
198 worker_thread
= WorkerThread(self
, id)
199 worker_threads
.append(worker_thread
)
201 return worker_threads
203 def initialise_timer_queue(self
):
204 for p
in self
.plugins
:
205 timer
= PluginTimer(p
)
207 self
._timer
_queue
.put(timer
)
209 def process_timer_queue(self
):
210 # Take the item from the timer queue that is to be due first
211 timer
= self
._timer
_queue
.get()
214 # If the timer event is to be executed, we will put the plugin
215 # into the worker queue and reset the timer
217 self
._worker
_queue
.put(timer
.plugin
)
218 timer
.reset_deadline()
222 # Put the timer back into the timer queue.
223 self
._timer
_queue
.put(timer
)
226 class WorkerThread(threading
.Thread
):
229 def __init__(self
, collecty
, id):
230 threading
.Thread
.__init
__(self
)
233 self
.log
= logging
.getLogger("collecty.worker")
234 self
.log
.propagate
= 1
236 self
.collecty
= collecty
239 self
.log
.debug(_("Worker thread %s has been initialised") % self
.id)
244 The queue this thread is getting events from
246 return self
.collecty
._worker
_queue
249 self
.log
.debug(_("Worker thread %s has been started") % self
.id)
254 plugin
= self
.queue
.get(block
=True, timeout
=self
.HEARTBEAT
)
256 # If the queue has been empty we just retry
260 # Execute the collect operation for this plugin
263 self
.log
.debug(_("Worker thread %s has been terminated") % self
.id)
268 # Wait until all data has been written.
272 class WriteQueue(threading
.Thread
):
273 def __init__(self
, collecty
, submit_interval
):
274 threading
.Thread
.__init
__(self
)
277 self
.collecty
= collecty
279 self
.log
= logging
.getLogger("collecty.queue")
280 self
.log
.propagate
= 1
282 self
.timer
= plugins
.Timer(submit_interval
)
283 self
._queue
= queue
.PriorityQueue()
285 self
.log
.debug(_("Initialised write queue"))
288 self
.log
.debug(_("Write queue process started"))
295 # Wait until the timer has successfully elapsed.
296 if self
.timer
.wait():
300 self
.log
.debug(_("Write queue process stopped"))
306 # Wait until all data has been written.
309 def add(self
, object, time
, data
):
310 result
= QueueObject(object.file, time
, data
)
311 self
._queue
.put(result
)
315 Flushes the read data to disk.
317 # There is nothing to do if the queue is empty
318 if self
._queue
.empty():
319 self
.log
.debug(_("No data to commit"))
322 time_start
= time
.time()
324 self
.log
.debug(_("Submitting data to the databases..."))
326 # Get all objects from the queue and group them by the RRD file
327 # to commit them all at once
329 while not self
._queue
.empty():
330 result
= self
._queue
.get()
333 results
[result
.file].append(result
)
335 results
[result
.file] = [result
]
337 # Write the collected data to disk
338 for filename
, results
in results
.items():
339 self
._commit
_file
(filename
, results
)
341 duration
= time
.time() - time_start
342 self
.log
.debug(_("Emptied write queue in %.2fs") % duration
)
344 def _commit_file(self
, filename
, results
):
345 self
.log
.debug(_("Committing %(counter)s entries to %(filename)s") \
346 % { "counter" : len(results
), "filename" : filename
})
348 for result
in results
:
349 self
.log
.debug(" %s: %s" % (result
.time
, result
.data
))
352 rrdtool
.update(filename
, *["%s" % r
for r
in results
])
354 # Catch operational errors like unreadable/unwritable RRD databases
355 # or those where the format has changed. The collected data will be lost.
356 except rrdtool
.OperationalError
as e
:
357 self
.log
.critical(_("Could not update RRD database %s: %s") \
361 class QueueObject(object):
362 def __init__(self
, file, time
, data
):
368 return "%s:%s" % (self
.time
.strftime("%s"), self
.data
)
370 def __cmp__(self
, other
):
371 return cmp(self
.time
, other
.time
)
374 class PluginTimer(object):
375 def __init__(self
, plugin
):
378 self
.deadline
= datetime
.datetime
.utcnow()
381 return "<%s %s>" % (self
.__class
__.__name
__, self
.deadline
)
383 def __cmp__(self
, other
):
384 return cmp(self
.deadline
, other
.deadline
)
386 def reset_deadline(self
):
387 self
.deadline
= datetime
.datetime
.utcnow() \
388 + datetime
.timedelta(seconds
=self
.plugin
.interval
)
391 return datetime
.datetime
.utcnow() >= self
.deadline