Skip to content

Instantly share code, notes, and snippets.

@arslanm
Created July 21, 2017 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arslanm/83ab877f4c9a550cb2d593f2666091b2 to your computer and use it in GitHub Desktop.
Save arslanm/83ab877f4c9a550cb2d593f2666091b2 to your computer and use it in GitHub Desktop.
Check number of delivered emails by postfix for netdata
#!/usr/bin/env python
import os, sys, time
import socket, threading
from pwd import getpwnam
class tail(object):
def __init__(self, file):
self.file = file
def check(self):
if not os.access(self.file, os.F_OK): raise
if not os.access(self.file, os.R_OK): raise
if os.path.isdir(self.file): raise
def lines(self):
self.check()
while 1:
s = 1
try:
with open(self.file) as f:
f.seek(0, 2)
while 1:
l = f.readline()
if not l:
if not s: break
time.sleep(s)
s = 0
else:
yield l
time.sleep(s)
except: pass
class postfix_delivered(object):
def __init__(self, sock = "/etc/postfix/postfix_delivered.sock"):
self.sock = sock
self.counter = 0
try:
os.unlink(self.sock)
except OSError:
if os.path.exists(self.sock): raise
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.socket.bind(self.sock)
try: id = getpwnam("netdata")[2]
except KeyError: raise
os.chown(self.sock, id, -1)
self.socket.listen(5)
self.lock = threading.Lock()
self.thread = threading.Thread(target = self.run, args = ())
self.thread.daemon = True
self.thread.start()
def run(self):
while 1:
c, _ = self.socket.accept()
with self.lock:
counter, self.counter = self.counter, 0
try:
c.sendall(str(counter))
finally:
c.close()
self.socket.close()
def inc(self):
with self.lock:
self.counter += 1
if __name__ == '__main__':
pd = postfix_delivered()
t = tail("/var/log/maillog")
for line in t.lines():
if not "status=sent" in line: continue
pd.inc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment