mailping-0.0.4/ 0002755 0001750 0001750 00000000000 10736203430 012337 5 ustar thijs thijs mailping-0.0.4/bin/ 0002755 0001750 0001750 00000000000 10157373374 013123 5 ustar thijs thijs mailping-0.0.4/bin/mailping-store 0000755 0001750 0001750 00000004041 10040000030 015737 0 ustar thijs thijs #!/usr/bin/python
"""
Store email from stdin to a mailping incoming maildir.
"""
__copyright__ = "Copyright (C) 2004 Tommi Virtanen"
__license__ = """
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 2 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 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
"""
import sys, os, time
from MailPing import config, maildir
def main():
statedir = config.getStateDir()
ext = os.environ.get('EXTENSION', None)
if ext is None:
mdir = os.path.join('Maildir')
else:
for c in ext:
if c not in '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_':
print >>sys.stderr, \
'%(progname)s: extension is unsafe, aborting.' \
% { 'progname': os.path.basename(sys.argv[0]), }
sys.exit(1)
mdir = os.path.join('state', ext, 'incoming')
path = os.path.join(statedir, mdir)
maildir.deliverToMaildir(path, sys.stdin)
if __name__ == '__main__':
if sys.argv[1:]:
print >>sys.stderr, \
'%(progname)s: parameters are not allowed.' \
% { 'progname': os.path.basename(sys.argv[0]), }
sys.exit(1)
try:
main()
except config.NoSuchConfigItem, e:
print >>sys.stderr, \
'%(progname)s: missing configuration file: %(name)s' \
% { 'progname': os.path.basename(sys.argv[0]),
'name': e[0],
}
sys.exit(1)
mailping-0.0.4/bin/mailping-cron 0000755 0001750 0001750 00000005126 10040000030 015551 0 ustar thijs thijs #!/usr/bin/python
"""
Run periodic processing to test email service availability and functioning.
"""
__copyright__ = "Copyright (C) 2004 Tommi Virtanen"
__license__ = """
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 2 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 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
"""
import sys, os, time, pwd, socket
from MailPing import config, incoming, probe
def main():
configdir = config.getConfigDir()
statedir = config.getStateDir()
for dirname in os.listdir(configdir):
configPath = os.path.join(configdir, dirname)
statePath = os.path.join(statedir, 'state', dirname)
if not os.path.isdir(statePath):
os.mkdir(statePath)
interval = config.getTime(configPath, 'interval', 10*60)
fromAddress = config.getEmail(configPath, 'from', None)
toAddress = config.getEmail(configPath, 'to', None)
if fromAddress is None or toAddress is None:
user = pwd.getpwuid(os.getuid()).pw_name
host = socket.getfqdn()
if fromAddress is None:
fromAddress = '%s@%s' % (user, host)
if toAddress is None:
toAddress = '%s+%s@%s' % (user, dirname, host)
adminAddress = config.getEmail(configPath, 'admin', None)
curtime = time.time()
if os.path.isdir(os.path.join(statePath, 'incoming')):
incoming.process(statePath)
probe.process(statePath, interval, curtime,
fromAddress, toAddress, adminAddress)
if __name__ == '__main__':
if sys.argv[1:]:
print >>sys.stderr, \
'%(progname)s: parameters are not allowed.' \
% { 'progname': os.path.basename(sys.argv[0]), }
sys.exit(1)
try:
main()
except config.NoSuchConfigItem, e:
print >>sys.stderr, \
'%(progname)s: missing configuration file: %(name)s' \
% { 'progname': os.path.basename(sys.argv[0]),
'name': e[0],
}
sys.exit(1)
mailping-0.0.4/man/ 0002755 0001750 0001750 00000000000 10622707632 013121 5 ustar thijs thijs mailping-0.0.4/man/mailping-latency.1.xml 0000644 0001750 0001750 00000011024 10040000151 017203 0 ustar thijs thijs
TommiVirtanenHavoc Consultingtv@havoc.fi
mailping
2004-04-16
2004Havoc Consultingmailping-latency1mailping-latencyMunin plugin to graph latency of mail deliveries/usr/share/mailping/munin-plugins/mailping-latencyconfig''Descriptionmailping-latency is a Munin plugin that monitors
the time spent between email submit and it's delivery.
Configuration output
When passed , it outputs Munin
configuration information. If there are no circuits defined (no
subdirectories in /etc/mailping), it
specifies that Munin should draw no graph either.
If configuration files
/etc/mailping/circuit/warnlatency
and
/etc/mailping/circuit/faillatency
exist, the values in them are passed on to Munin, for use in
Nagios alert integration.
Value output
When passed an empty string ,
mailping-latency outputs latency of last
successful probe message, for each configured circuit.
Files/etc/mailping/
List of circuits that exist; each subdirectory is a circuit.
/etc/mailping/circuit/warnlatency
If latency is greater than this many seconds, a Nagios
warning is triggered by Munin (assuming it has been
configured to do that).
Default: no warnings.
/etc/mailping/circuit/faillatency
If latency is greater than this many seconds, a Nagios
alert is triggered by Munin (assuming it has been
configured to do that).
Default: no alerts.
/var/lib/mailping/state/circuit/latency
Amount of latency in seconds of the last successful probe
for circuit.
EnvironmentMAILPING_CONFIGDIR
Override the location of the configuration directory.
Default: /etc/mailpingMAILPING_STATEDIR
Override the location of the state directory. Circuit
states are stored in the state
subdirectory of this directory, in subdirectories named
after the circuit name.
Default: /var/lib/mailpingSee Also,
,
,
munin-run(8),
munin-node(8)
mailping-0.0.4/man/mailping-store.1.xml 0000644 0001750 0001750 00000010171 10037777410 016733 0 ustar thijs thijs
TommiVirtanenHavoc Consultingtv@havoc.fi
mailping
2004-04-15
2004Havoc Consultingmailping-store1mailping-storestore email from stdin to a mailping incoming maildirmailping-storeDescriptionmailping-store reads an email from standard input
and writes it into a maildir chosen according to following logic:
If EXTENSION is not set, select
Maildir.
If EXTENSION is set, ensure its value is
safe to use, and select
EXTENSION/incoming.
mailping-store is usually run from a
.forward file, and thus the filenames
above are relative to the home directory of the account
in question.
Normal use
Normally, mailping-store is used to ease
the setup of new circuits to probe from
mailping-cron. This is done with a system
account mailping
using
mailping@yourhost.example.com
as the from address, and
mailping+circuitname@yourhost.example.com
(or some remote address aliased to that) as the
to address. In fact, these are the default
values for from and to,
so you can just skip creating those configuration files.
This allows adding new test circuits without any changes to
the email configuration.
Files/var/lib/mailping/state/circuit/incoming
Maildir to store the email to.
/var/lib/mailping/state/Maildir/
Maildir to store the email to, if no extension was given.
EnvironmentMAILPING_STATEDIR
Override the location of the state directory. Circuit
states are stored in the state
subdirectory of this directory, in subdirectories named
after the circuit name.
Default: /var/lib/mailpingEXTENSION
Name of the current circuit to store the mail for.
See Also,
,
mailping-0.0.4/man/mailping-cron.1.xml 0000644 0001750 0001750 00000015727 10037777410 016554 0 ustar thijs thijs
TommiVirtanenHavoc Consultingtv@havoc.fi
mailping
2004-04-15
2004Havoc Consultingmailping-cron1mailping-cronrun periodic processing to test email service availability and functioningmailping-cronDescriptionmailping-cron processes incoming emails,
updates status and sends out probe messages.
The idea is to configure multiple email circuits,
send probe messages regularly, and see whether they complete
the circuit and how long it took.
Setting up a circuit
Give a name to the circuit, hereafter referred to as
circuit.
Arrange for a local email address to be delivered to
maildir
/var/lib/mailping/state/circuit/incoming/.
See mailping-store.
Create a configuration for the circuit, by creating
directory
/etc/mailping/circuit.
If you need non-default sender and/or recipient addresses,
create files from and
to there, containing the sender and
recipient addresses suitable for the circuit.
You're done! Munin should now see the data.
Testing multiple servers
To test functioning of more than one email server, arrange
an email alias at a remote site pointing to an address on
your server, and set the address of that alias here.
Here's an example of testing a system consisting of two
email servers and everything in that path (smarthosts,
primary MXs, virus checkers, etc.):
Local address mailping+that@this.example.com
is delivered with mailping-store to
/var/lib/mailping/state/that/incoming/.
Remote address echo@that.example.com is
an alias that redirects all email to
mailping+that@this.example.com.
/etc/mailping/that/to is set to
echo@that.example.com.
Files/etc/mailping/circuit/from
Sender address for the probe emails.
Default:
currentuserid@fullyqualifiedhostname.
/etc/mailping/circuit/to
Recipient address for the probe emails. You must arrange
for the email to eventually get delivered to the maildir
/var/lib/mailping/state/circuit/incoming/.
mailping-store will probably be useful in that.
Default:
currentuserid+circuit@fullyqualifiedhostname/etc/mailping/circuit/admin
Admistrative address, set as Reply-To
in probe messages. Default: do not add
Reply-To.
/etc/mailping/circuit/interval
How often a probe message is sent, in seconds. Default: 600 seconds.
/var/lib/mailping/state/circuit/
Stored state for the probing.
/var/lib/mailping/state/circuit/junk/
Maildir used to store all messages in
incoming that do not look like probe
messages. Read and delete them regularly.
/var/lib/mailping/state/circuit/broken/
Maildir used to store all messages in
incoming that do look like probe
messages, but a corresponding pending
entry cannot be found. Duplicated probe messages cause
these. Read and delete them regularly.
EnvironmentMAILPING_CONFIGDIR
Override the location of the configuration directory.
Default: /etc/mailpingMAILPING_STATEDIR
Override the location of the state directory. Circuit
states are stored in the state
subdirectory of this directory, in subdirectories named
after the circuit name.
Default: /var/lib/mailpingSee Also,
,
mailping-0.0.4/man/man.xml 0000644 0001750 0001750 00000001050 10037777410 014411 0 ustar thijs thijs
Mailping
mailping-0.0.4/man/man.xsl 0000644 0001750 0001750 00000004535 10037573440 014427 0 ustar thijs thijs
, \fI\fP\fB\fP\fB\fP<>
.PP
mailping-0.0.4/man/run 0000755 0001750 0001750 00000000075 10037777335 013662 0 ustar thijs thijs #!/bin/sh
set -e
xsltproc --xinclude --nonet man.xsl man.xml
mailping-0.0.4/man/mailping-success.1.xml 0000644 0001750 0001750 00000011104 10040000151 017213 0 ustar thijs thijs
TommiVirtanenHavoc Consultingtv@havoc.fi
mailping
2004-04-16
2004Havoc Consultingmailping-success1mailping-successMunin plugin to graph time since last mail delivery/usr/share/mailping/munin-plugins/mailping-successconfig''Descriptionmailping-success is a Munin plugin that monitors
time passed since last successful email probe.
Configuration output
When passed , it outputs Munin
configuration information. If there are no circuits defined (no
subdirectories in /etc/mailping), it
specifies that Munin should draw no graph either.
If configuration files
/etc/mailping/circuit/warntime
and
/etc/mailping/circuit/failtime
exist, the values in them are passed on to Munin, for use in
Nagios alert integration.
Value output
When passed an empty string ,
mailping-success outputs the difference between current time
and last successful probe, for each configured circuit.
Files/etc/mailping/
List of circuits that exist; each subdirectory is a circuit.
/etc/mailping/circuit/warntime
If more than this many seconds have passed since last
successful probe, a Nagios warning is triggered by Munin
(assuming it has been configured to do that).
Default: no warnings.
/etc/mailping/circuit/failtime
If more than this many seconds have passed since last
successful probe, a Nagios alert is triggered by Munin
(assuming it has been configured to do that).
Default: no alerts.
/var/lib/mailping/state/circuit/success
Timestamp in seconds of the last successful probe for
circuit.
EnvironmentMAILPING_CONFIGDIR
Override the location of the configuration directory.
Default: /etc/mailpingMAILPING_STATEDIR
Override the location of the state directory. Circuit
states are stored in the state
subdirectory of this directory, in subdirectories named
after the circuit name.
Default: /var/lib/mailpingSee Also,
,
,
munin-run(8),
munin-node(8)
mailping-0.0.4/munin-plugins/ 0002755 0001750 0001750 00000000000 10157373374 015160 5 ustar thijs thijs mailping-0.0.4/munin-plugins/mailping-success 0000755 0001750 0001750 00000004721 10040014610 020326 0 ustar thijs thijs #!/usr/bin/python
"""
Munin plugin to graph time since last mail delivery
"""
__copyright__ = "Copyright (C) 2004 Tommi Virtanen"
__license__ = """
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 2 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 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
"""
import sys, os, time
def config():
from MailPing import config
print 'graph_title Mailping time since last success'
print 'graph_vlabel seconds'
configdir = config.getConfigDir()
circuits = os.listdir(configdir)
if not circuits:
print 'graph no'
else:
for dirname in circuits:
name = dirname
path = os.path.join(configdir, dirname)
print '%s.label %s' % (name, dirname)
print '%s.min 0' % name
try:
print '%s.warning %f' % (name, config.getTime(path, 'warntime'))
except config.NoSuchConfigItem:
pass
try:
print '%s.critical %f' % (name, config.getTime(path, 'failtime'))
except config.NoSuchConfigItem:
pass
def dump():
from MailPing import fileutil, config
configdir = config.getConfigDir()
statedir = config.getStateDir()
for dirname in os.listdir(configdir):
if os.path.isdir(os.path.join(statedir, 'state', dirname)):
name = dirname
success = fileutil.getTime(os.path.join(statedir, 'state', dirname, 'success'))
if success >= 0:
print '%s.value %f' % (name, time.time() - success)
if __name__ == '__main__':
if len(sys.argv[1:]) == 1 and sys.argv[1] == 'config':
config()
elif len(sys.argv[1:]) == 1 and sys.argv[1] == '':
dump()
else:
print >>sys.stderr, "%(progname)s: usage: %(progname)s [config|'']" \
% { 'progname': os.path.basename(sys.argv[0]),
}
sys.exit(1)
mailping-0.0.4/munin-plugins/mailping-latency 0000755 0001750 0001750 00000004667 10040014610 020326 0 ustar thijs thijs #!/usr/bin/python
"""
Munin plugin to graph latency of mail deliveries
"""
__copyright__ = "Copyright (C) 2004 Tommi Virtanen"
__license__ = """
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 2 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 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
"""
import sys, os, time
def config():
from MailPing import config
print 'graph_title Mailping latency'
print 'graph_vlabel seconds'
configdir = config.getConfigDir()
circuits = os.listdir(configdir)
if not circuits:
print 'graph no'
else:
for dirname in circuits:
name = dirname
path = os.path.join(configdir, dirname)
print '%s.label %s' % (name, dirname)
print '%s.min 0' % name
try:
print '%s.warning %f' % (name, config.getTime(path, 'warnlatency'))
except config.NoSuchConfigItem:
pass
try:
print '%s.critical %f' % (name, config.getTime(path, 'faillatency'))
except config.NoSuchConfigItem:
pass
def dump():
from MailPing import fileutil, config
configdir = config.getConfigDir()
statedir = config.getStateDir()
for dirname in os.listdir(configdir):
if os.path.isdir(os.path.join(statedir, 'state', dirname)):
name = dirname
latency = fileutil.getTime(os.path.join(statedir, 'state', dirname, 'latency'))
if latency >= 0:
print '%s.value %f' % (name, latency)
if __name__ == '__main__':
if len(sys.argv[1:]) == 1 and sys.argv[1] == 'config':
config()
elif len(sys.argv[1:]) == 1 and sys.argv[1] == '':
dump()
else:
print >>sys.stderr, "%(progname)s: usage: %(progname)s [config|'']" \
% { 'progname': os.path.basename(sys.argv[0]),
}
sys.exit(1)
mailping-0.0.4/COPYING 0000644 0001750 0001750 00000043110 10037742112 013366 0 ustar thijs thijs GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
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 2 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 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
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.
mailping-0.0.4/README 0000644 0001750 0001750 00000003657 10040014610 013214 0 ustar thijs thijs Mailping
========
monitor email service availability _and_ functioning.
Please read the man pages mailping-cron(1) and mailping-store(1) for
real documentation. This file is just a random collection of notes,
for now.
Overview of files
-----------------
configdir:
from
to
(admin)
interval
warntime
failtime
warnlatency
faillatency
statedir:
pending/
incoming/{tmp,cur,new}
broken/{tmp,cur,new} # valid-looking messages without
# corresponding pendings go here
junk/{tmp,cur,new} # invalid messages go here
success
Rough overview of the internal processing
-----------------------------------------
- for incoming mail
- parse mail to find identifier
- if no identifier, move message to junk/
- if got identifier, find matching entry in pending/
- if not found, move message to broken/
- if found
- if getTime(pending/$THIS) > getTime(success)
- then rename to "success"
- else remove
- if max(getTime("success"), getTime("pending/*")) + interval < time:
- send new probe
- create pending/$THIS
Installation instructions for non-Debian
----------------------------------------
These steps are only needed if you are not using Debian. For Debian
users, these have been taken care of by the maintainer scripts.
Install the software with the usual python distutils stuff, run
"python setup.py install" as root.
Arrange for mailping-cron to be run from cron regularly. It must have
write access to statedir -- I suggest you create a user "mailping"
with homedir /var/lib/mailping (owned by root:root), and make mailping
own /var/lib/mailping/state.
Arrange for email to e.g. mailping+FOO@something to be delivered to
/var/lib/mailping/state/FOO/incoming/. If you created the user above,
just create /var/lib/mailping/.forward with "|/usr/bin/mailping-store"
and things should work.
Register the plugins mailping-success and mailping-latency with munin.
Restart munin-node to make it notice the now plugins.
mailping-0.0.4/setup.py 0000644 0001750 0001750 00000003500 10037732217 014051 0 ustar thijs thijs #!/usr/bin/env python
from distutils.core import setup
if __name__=='__main__':
setup(name='mailping',
description='monitor email service availability and functioning',
long_description="""
Monitor email service availability and functioning. Tests the whole
route from SMTP submission to local delivery, not just whether an SMTP
server accepts TCP connections.
Multiple email servers can be tested by creating a remote alias that
points back to a local address, and sending test emails to it.
The results of this monitoring are available as graphs via Munin
plugins, and can be connected to Nagios to send alerts when the test
emails no longer get delivered, or if the delivery takes too long.
""".strip(),
author="Tommi Virtanen",
author_email="tv@havoc.fi",
#url="http://TODO/",
license="GNU GPL",
packages=['MailPing', 'MailPing.test'],
scripts=['bin/mailping-cron',
'bin/mailping-store',
],
data_files=[
['share/mailping/munin-plugins', ['munin-plugins/mailping-success',
'munin-plugins/mailping-latency',
]],
],
classifiers=[
'Development Status :: 3 - Alpha',
#'Development Status :: 4 - Beta',
#'Development Status :: 5 - Production/Stable',
'Environment :: No Input/Output (Daemon)',
'Environment :: Plugins',
'Intended Audience :: System Administrators',
'License :: DFSG approved',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: Unix',
'Programming Language :: Python',
'Topic :: Communications :: Email',
'Topic :: Internet',
'Topic :: System :: Monitoring',
],
)
mailping-0.0.4/doc/ 0002755 0001750 0001750 00000000000 10157373374 013120 5 ustar thijs thijs mailping-0.0.4/doc/examples/ 0002755 0001750 0001750 00000000000 10157373374 014736 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/ 0002755 0001750 0001750 00000000000 10157373374 016056 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/broken/ 0002755 0001750 0001750 00000000000 10157373374 017336 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/broken/new/ 0002755 0001750 0001750 00000000000 10157373374 020127 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/broken/tmp/ 0002755 0001750 0001750 00000000000 10157373374 020136 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/broken/cur/ 0002755 0001750 0001750 00000000000 10157373374 020127 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/pending/ 0002755 0001750 0001750 00000000000 10157373374 017502 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/junk/ 0002755 0001750 0001750 00000000000 10157373374 017025 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/junk/new/ 0002755 0001750 0001750 00000000000 10157373374 017616 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/junk/tmp/ 0002755 0001750 0001750 00000000000 10157373374 017625 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/junk/cur/ 0002755 0001750 0001750 00000000000 10157373374 017616 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/incoming/ 0002755 0001750 0001750 00000000000 10157373374 017661 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/incoming/new/ 0002755 0001750 0001750 00000000000 10157373374 020452 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/incoming/tmp/ 0002755 0001750 0001750 00000000000 10157373374 020461 5 ustar thijs thijs mailping-0.0.4/doc/examples/state/incoming/cur/ 0002755 0001750 0001750 00000000000 10157373374 020452 5 ustar thijs thijs mailping-0.0.4/doc/examples/config/ 0002755 0001750 0001750 00000000000 10157373374 016203 5 ustar thijs thijs mailping-0.0.4/doc/examples/config/to 0000644 0001750 0001750 00000000023 10037211452 016522 0 ustar thijs thijs mailping@localhost
mailping-0.0.4/doc/examples/config/admin 0000644 0001750 0001750 00000000017 10037211452 017173 0 ustar thijs thijs root@localhost
mailping-0.0.4/doc/examples/config/failtime 0000644 0001750 0001750 00000000004 10037211452 017671 0 ustar thijs thijs 300
mailping-0.0.4/doc/examples/config/from 0000644 0001750 0001750 00000000023 10037211452 017043 0 ustar thijs thijs mailping@localhost
mailping-0.0.4/doc/examples/config/interval 0000644 0001750 0001750 00000000003 10037211452 017722 0 ustar thijs thijs 60
mailping-0.0.4/doc/examples/dot-forward 0000644 0001750 0001750 00000000033 10037332732 017071 0 ustar thijs thijs "|/usr/bin/mailping-store"
mailping-0.0.4/MailPing/ 0002755 0001750 0001750 00000000000 10157373374 014053 5 ustar thijs thijs mailping-0.0.4/MailPing/maildir.py 0000644 0001750 0001750 00000004611 10040013501 016014 0 ustar thijs thijs import os, errno, time, socket
def _mkdir(*a, **kw):
try:
os.mkdir(*a, **kw)
except OSError, e:
if e.errno == errno.EEXIST:
pass
else:
raise
def create(path):
_mkdir(path)
_mkdir(os.path.join(path, 'cur'), 0700)
_mkdir(os.path.join(path, 'new'), 0700)
_mkdir(os.path.join(path, 'tmp'), 0700)
def process(path, callback):
for subdir in [os.path.join(path, 'new'),
os.path.join(path, 'cur')]:
for filename in os.listdir(subdir):
callback(subdir, filename)
def getTimeFromFilename(filename):
"""
Extract the delivery timestamp from a maildir message filename.
See http://cr.yp.to/proto/maildir.html for more information.
(Yes, I know DJB doesn't want people parsing the filenames.)
Also parses microseconds when available. Return type is float when
subsecond precision is possible, int otherwise.
"""
# strip off potential info
filename = filename.split(':', 1)[0]
try:
time, delivery, hostname = filename.split('.', 2)
except ValueError:
return None
try:
seconds = int(time)
except ValueError:
return None
if delivery and delivery[0] not in '012345679':
# looks like a new-style delivery identifier
try:
i = delivery.index('M')
except ValueError:
pass
else:
rest = delivery[i+1:]
s = ''
while rest and rest[0] in '0123456789':
s = s + rest[0]
rest = rest[1:]
if s:
try:
microseconds = int(s)
except ValueError:
pass
else:
return float(seconds + microseconds * 1e-6)
return int(seconds)
def generateMaildirName():
curtime = time.time()
return '%s.M%sP%s.%s' % (
int(curtime),
int((curtime-int(curtime))*10e6),
os.getpid(),
socket.gethostname().replace('/', r'\057').replace(':', r'\072')
)
def deliverToMaildir(path, source):
create(path)
filename = generateMaildirName()
tmp = os.path.join(path, 'tmp', filename)
f = file(tmp, 'w')
while True:
data = source.read(8192)
if not data:
break
f.write(data)
f.close()
os.rename(tmp, os.path.join(path, 'new', filename))
mailping-0.0.4/MailPing/mail.py 0000644 0001750 0001750 00000001512 10040013501 015312 0 ustar thijs thijs from email.Parser import Parser as EmailParser
def getID(path):
f = file(path)
p = EmailParser()
msg = p.parse(f, True)
f.close()
subj = msg.get('Subject')
if subj is not None:
if subj.startswith('Mail ping '):
subj = subj[len('Mail ping '):]
else:
subj = None
return subj
class TemplateMustNotHaveFieldError(Exception):
"""Probe email template must not have this field"""
def __str__(self):
return '%s: %r, %r' % (self.__doc__,
self[0],
self[1])
def setMsgField(msg, field, value):
if msg[field] is not None:
raise TemplateMustNotHaveFieldError, (field, msg[field])
msg[field] = value
def setID(msg, ident):
setMsgField(msg, 'Subject', 'Mail ping %s' % ident)
mailping-0.0.4/MailPing/config.py 0000644 0001750 0001750 00000002113 10040014610 015635 0 ustar thijs thijs import os, errno
from MailPing import fileutil
class NoSuchConfigItem(Exception):
"""Configuration item does not exist."""
class _NoDefault:
pass
def getTime(configdir, name, default=_NoDefault):
t = fileutil.getTime(os.path.join(configdir, name))
if t < 0:
if default is _NoDefault:
raise NoSuchConfigItem, name
else:
t = default
return t
def getEmail(configdir, name, default=_NoDefault):
path = os.path.join(configdir, name)
try:
f=file(path)
except IOError, e:
if e.errno == errno.ENOENT:
if default is _NoDefault:
raise NoSuchConfigItem, name
else:
return default
else:
raise
l=f.readline()
l=l.strip()
return l
DEFAULT_CONFIGDIR = '/etc/mailping'
DEFAULT_STATEDIR = '/var/lib/mailping'
def getConfigDir():
return os.environ.get('MAILPING_CONFIGDIR',
DEFAULT_CONFIGDIR)
def getStateDir():
return os.environ.get('MAILPING_STATEDIR',
DEFAULT_STATEDIR)
mailping-0.0.4/MailPing/fileutil.py 0000644 0001750 0001750 00000001156 10040014610 016213 0 ustar thijs thijs import os, errno, time, socket
HOSTNAME = socket.gethostname().replace('/', r'\057').replace(':', r'\072')
PID = os.getpid()
def getTime(path):
try:
f=open(path)
except IOError, e:
if e.errno == errno.ENOENT:
return -1
else:
raise
l=f.readline()
return float(l)
def writeFile(path, content, temp=None):
if temp is None:
temp = '%s.%d.%s.%d.tmp' % (
path,
int((time.time())*10e6),
HOSTNAME,
PID,
)
f = file(temp, 'w')
f.write(content)
f.close()
os.rename(temp, path)
mailping-0.0.4/MailPing/test/ 0002755 0001750 0001750 00000000000 10157373374 015032 5 ustar thijs thijs mailping-0.0.4/MailPing/test/test_mail.py 0000644 0001750 0001750 00000007421 10040013501 017335 0 ustar thijs thijs from twisted.trial import unittest
import os, sets, email
from MailPing import mail, maildir, fileutil
class TestMail(unittest.TestCase):
def setUp(self):
self.maildir = self.mktemp()
os.mkdir(self.maildir)
os.mkdir(os.path.join(self.maildir, 'cur'))
os.mkdir(os.path.join(self.maildir, 'new'))
os.mkdir(os.path.join(self.maildir, 'tmp'))
def testGetID_Simple(self):
fileutil.writeFile(os.path.join(self.maildir, 'new',
'42.P34Q0.testhost'),
'''\
From: Foo Bar
To: Mr. You
Subject: Mail ping f0e241677fa9f2e0d7884776e4a6846b19703e6d
Reply-To: admin@foo.invalid
content is just junk
''')
seen = sets.Set()
def _store(path, filename):
x = mail.getID(os.path.join(path, filename))
seen.add((filename, x))
maildir.process(os.path.join(self.maildir),
_store)
self.assertEquals(seen,
sets.Set([
('42.P34Q0.testhost', 'f0e241677fa9f2e0d7884776e4a6846b19703e6d'),
]))
def testGetID_NoSubject(self):
fileutil.writeFile(os.path.join(self.maildir, 'new',
'42.P34Q0.testhost'),
'''\
From: Foo Bar
To: Mr. You
Reply-To: admin@foo.invalid
content is just junk
''')
seen = sets.Set()
def _store(path, filename):
x = mail.getID(os.path.join(path, filename))
seen.add((filename, x))
maildir.process(os.path.join(self.maildir),
_store)
self.assertEquals(seen,
sets.Set([
('42.P34Q0.testhost', None),
]))
def testGetID_InvalidSubject(self):
msgpath = os.path.join(self.maildir, 'new',
'42.P34Q0.testhost')
fileutil.writeFile(msgpath,
'''\
From: Foo Bar
To: Mr. You
Subject: SPAM SPAM SPAM!
Reply-To: admin@foo.invalid
content is just junk
''')
seen = sets.Set()
def _store(path, filename):
x = mail.getID(os.path.join(path, filename))
seen.add((filename, x))
maildir.process(os.path.join(self.maildir),
_store)
self.assertEquals(seen,
sets.Set([
('42.P34Q0.testhost', None),
]))
def testSetID_OK(self):
msg = email.message_from_string('''\
From: Foo Bar
To: Mr. You
Reply-To: admin@foo.invalid
content is just junk
''')
mail.setID(msg, 'f0e241677fa9f2e0d7884776e4a6846b19703e6d')
self.assertEquals(msg.as_string(),
'''\
From: Foo Bar
To: Mr. You
Reply-To: admin@foo.invalid
Subject: Mail ping f0e241677fa9f2e0d7884776e4a6846b19703e6d
content is just junk
''')
def testSetID_HasSubject(self):
msg = email.message_from_string('''\
From: Foo Bar
Subject: I should not be here
To: Mr. You
Reply-To: admin@foo.invalid
content is just junk
''')
self.assertRaises(mail.TemplateMustNotHaveFieldError,
mail.setID,
msg, 'f0e241677fa9f2e0d7884776e4a6846b19703e6d')
try:
mail.setID(msg, 'f0e241677fa9f2e0d7884776e4a6846b19703e6d')
except mail.TemplateMustNotHaveFieldError, e:
self.assertEquals(
str(e),
"Probe email template must not have this field: "
+ "'Subject', 'I should not be here'")
mailping-0.0.4/MailPing/test/test_incoming.py 0000644 0001750 0001750 00000017327 10040015764 020241 0 ustar thijs thijs from twisted.trial import unittest
import os, sets
from cStringIO import StringIO
from MailPing import maildir, incoming, fileutil
class TestIncoming(unittest.TestCase):
def setUp(self):
self.statedir = self.mktemp()
os.mkdir(self.statedir)
os.mkdir(os.path.join(self.statedir, 'pending'))
for name in ['incoming', 'broken', 'junk']:
path = os.path.join(self.statedir, name)
os.mkdir(path)
os.mkdir(os.path.join(path, 'cur'))
os.mkdir(os.path.join(path, 'new'))
os.mkdir(os.path.join(path, 'tmp'))
def assert_empty_maildir(self, maildir):
for subdir in ['cur', 'new', 'tmp']:
path = os.path.join(self.statedir, maildir, subdir)
contents = os.listdir(path)
self.assertEquals(contents, [],
'Maildir %r should be empty, but contains %r' % (path, contents))
def assert_maildirs_empty(self):
for maildir in ['incoming', 'broken', 'junk']:
self.assert_empty_maildir(maildir)
def assert_pending_empty(self):
path = os.path.join(self.statedir, 'pending')
contents = os.listdir(path)
self.assertEquals(contents, [],
'Pending %r should be empty, but contains %r' % (path, contents))
def assert_no_success(self):
path = os.path.join(self.statedir, 'success')
self.failIf(os.path.exists(path))
path = os.path.join(self.statedir, 'success.msg')
self.failIf(os.path.exists(path))
path = os.path.join(self.statedir, 'latency')
self.failIf(os.path.exists(path))
def assert_success(self, timestamp, content=None, latency=None):
path = os.path.join(self.statedir, 'success')
lastSuccess = fileutil.getTime(path)
self.assertEquals(lastSuccess, timestamp)
if content is not None:
text = file(path+'.msg').read()
self.assertEquals(content, text)
if latency is not None:
got = fileutil.getTime(os.path.join(self.statedir, 'latency'))
self.assertEquals(got, latency)
def testProcessing_junk(self):
text = '''\
From: Foo Bar
To: Mr. You
Subject: SPAM SPAM SPAM!
Reply-To: admin@foo.invalid
content is just junk
'''
fileutil.writeFile(
os.path.join(self.statedir, 'incoming', 'new',
'42.P34Q0.testhost'),
text)
incoming.process(self.statedir)
filename = os.path.join(self.statedir, 'junk', 'new',
'42.P34Q0.testhost')
self.failUnless(os.path.isfile(filename))
content = file(filename).read()
self.assertEquals(text, content)
self.assert_empty_maildir('incoming')
self.assert_empty_maildir('broken')
self.assert_pending_empty()
self.assert_no_success()
def testProcessing_broken(self):
text = '''\
From: Foo Bar
To: Mr. You
Subject: Mail ping f0e241677fa9f2e0d7884776e4a6846b19703e6d
Reply-To: admin@foo.invalid
content is just junk
'''
fileutil.writeFile(
os.path.join(self.statedir, 'incoming', 'new',
'42.P34Q0.testhost'),
text)
incoming.process(self.statedir)
filename = os.path.join(self.statedir, 'broken', 'new',
'42.P34Q0.testhost')
self.failUnless(os.path.isfile(filename))
content = file(filename).read()
self.assertEquals(text, content)
self.assert_empty_maildir('incoming')
self.assert_empty_maildir('junk')
self.assert_pending_empty()
self.assert_no_success()
def testProcessing_older(self):
text = '''\
From: Foo Bar
To: Mr. You
Subject: Mail ping f0e241677fa9f2e0d7884776e4a6846b19703e6d
Reply-To: admin@foo.invalid
content is just junk
'''
fileutil.writeFile(os.path.join(self.statedir, 'success'),
'42\n')
fileutil.writeFile(
os.path.join(self.statedir, 'incoming', 'new',
'43.P34Q0.testhost'),
text)
fileutil.writeFile(
os.path.join(self.statedir, 'pending',
'f0e241677fa9f2e0d7884776e4a6846b19703e6d'),
'13\n')
incoming.process(self.statedir)
self.assert_maildirs_empty()
self.assert_pending_empty()
self.assert_success(content=None, timestamp=42, latency=-1)
def testProcessing_newer(self):
text = '''\
From: Foo Bar
To: Mr. You
Subject: Mail ping f0e241677fa9f2e0d7884776e4a6846b19703e6d
Reply-To: admin@foo.invalid
content is just junk
'''
fileutil.writeFile(os.path.join(self.statedir, 'success'),
'42\n')
fileutil.writeFile(
os.path.join(self.statedir, 'incoming', 'new',
'45.P34Q0.testhost'),
text)
fileutil.writeFile(
os.path.join(self.statedir, 'pending',
'f0e241677fa9f2e0d7884776e4a6846b19703e6d'),
'43\n')
incoming.process(self.statedir)
self.assert_maildirs_empty()
self.assert_pending_empty()
self.assert_success(content=text,
timestamp=43,
latency=2)
def testProcessing_Latency_BackInTime(self):
text = '''\
From: Foo Bar
To: Mr. You
Subject: Mail ping f0e241677fa9f2e0d7884776e4a6846b19703e6d
Reply-To: admin@foo.invalid
content is just junk
'''
fileutil.writeFile(os.path.join(self.statedir, 'success'),
'42\n')
fileutil.writeFile(
os.path.join(self.statedir, 'incoming', 'new',
'42.P34Q0.testhost'),
text)
fileutil.writeFile(
os.path.join(self.statedir, 'pending',
'f0e241677fa9f2e0d7884776e4a6846b19703e6d'),
'43\n')
incoming.process(self.statedir)
self.assert_maildirs_empty()
self.assert_pending_empty()
self.assert_success(content=text,
timestamp=43,
latency=-1)
def testProcessing_Latency_Unparseable(self):
text = '''\
From: Foo Bar
To: Mr. You
Subject: Mail ping f0e241677fa9f2e0d7884776e4a6846b19703e6d
Reply-To: admin@foo.invalid
content is just junk
'''
fileutil.writeFile(os.path.join(self.statedir, 'success'),
'42\n')
fileutil.writeFile(
os.path.join(self.statedir, 'incoming', 'new',
'garbage-in-nothing-out'),
text)
fileutil.writeFile(
os.path.join(self.statedir, 'pending',
'f0e241677fa9f2e0d7884776e4a6846b19703e6d'),
'43\n')
incoming.process(self.statedir)
self.assert_maildirs_empty()
self.assert_pending_empty()
self.assert_success(content=text,
timestamp=43,
latency=-1)
def testReceiveToNonExisting(self):
text = "Message for you, Sir"
msg = StringIO(text)
path = os.path.join(self.statedir, 'nonexisting')
maildir.deliverToMaildir(path, msg)
new = os.path.join(path, 'new')
self.failUnless(os.path.isdir(new))
l = os.listdir(new)
self.assertEquals(len(l), 1)
f = file(os.path.join(new, l[0]))
got = f.read()
self.assertEquals(got, text)
mailping-0.0.4/MailPing/test/test_fileutil.py 0000644 0001750 0001750 00000000701 10040014610 020224 0 ustar thijs thijs from twisted.trial import unittest
import os, sets
from MailPing import fileutil
class TestFileUtil(unittest.TestCase):
def testTimestampRead(self):
filename = self.mktemp()
f=file(filename, 'w')
f.write('42\n')
f.close()
self.assertEquals(fileutil.getTime(filename), 42)
def testTimestampReadFail(self):
filename = self.mktemp()
self.assertEquals(fileutil.getTime(filename), -1)
mailping-0.0.4/MailPing/test/test_probe.py 0000644 0001750 0001750 00000007054 10037450144 017542 0 ustar thijs thijs from twisted.trial import unittest
import os, sets, string
from MailPing import probe, fileutil
class TestTiming(unittest.TestCase):
expected = [
({ 'success': 42,
'pending/f0e241677fa9f2e0d7884776e4a6846b19703e6d': 42,
},
10,
52,
False),
({ 'success': 42,
'pending/f0e241677fa9f2e0d7884776e4a6846b19703e6d': 42,
},
10,
53,
True),
({ 'success': 42,
'pending/f0e241677fa9f2e0d7884776e4a6846b19703e6d': 42,
},
50,
100,
True),
({ 'success': 52,
'pending/f0e241677fa9f2e0d7884776e4a6846b19703e6d': 42,
},
50,
100,
False),
({ 'success': 42,
'pending/f0e241677fa9f2e0d7884776e4a6846b19703e6d': 52,
},
50,
100,
False),
]
def setUp(self):
self.statedir = self.mktemp()
os.mkdir(self.statedir)
os.mkdir(os.path.join(self.statedir, 'pending'))
def testShouldOrShouldNot(self):
for data, interval, time, want in self.expected:
for filename, timestamp in data.items():
fileutil.writeFile(os.path.join(self.statedir, filename),
'%f\n' % timestamp)
got = probe.shouldSend(self.statedir,
interval,
time)
self.assertEquals(got, want)
class TestIdent(unittest.TestCase):
def testCreation(self):
ident = probe.randomIdent()
self.failUnless(isinstance(ident, str))
self.assertEquals(len(ident), 40)
for c in ident:
self.failUnless(c in string.hexdigits)
def testRandomness(self):
seen = sets.Set()
for i in range(20):
ident = probe.randomIdent()
self.failIf(ident in seen)
seen.add(ident)
class TestProbeMessage(unittest.TestCase):
def testMakeProbe(self):
msg = probe.makeProbe(
ident='f0e241677fa9f2e0d7884776e4a6846b19703e6d',
fromAddress='The Sender ',
toAddress='Recipient, The ')
msgid = msg['Message-ID']
del msg['Message-ID']
self.failUnless(msgid.startswith('<'))
self.failUnless(msgid.endswith('>'))
msgid = msgid[1:-1]
lead, host = msgid.split('@', 1)
self.failUnless(lead.endswith('.mailping.f0e241677fa9f2e0d7884776e4a6846b19703e6d'))
lead = lead[:-len('.mailping.f0e241677fa9f2e0d7884776e4a6846b19703e6d')]
for c in lead:
self.failUnless(c in '0123456789.')
self.assertEquals(msg.as_string(),
"""\
From: The Sender
To: Recipient, The
Subject: Mail ping f0e241677fa9f2e0d7884776e4a6846b19703e6d
""" + probe.MESSAGE_TEXT)
def testMakeProbeWithAdmin(self):
msg = probe.makeProbe(
ident='f0e241677fa9f2e0d7884776e4a6846b19703e6d',
fromAddress='The Sender ',
toAddress='Recipient, The ',
adminAddress='Administrator ')
del msg['Message-ID']
self.assertEquals(msg.as_string(),
"""\
From: The Sender
To: Recipient, The
Reply-To: Administrator
Subject: Mail ping f0e241677fa9f2e0d7884776e4a6846b19703e6d
""" + probe.MESSAGE_TEXT)
mailping-0.0.4/MailPing/test/test_config.py 0000644 0001750 0001750 00000002734 10037230631 017675 0 ustar thijs thijs from twisted.trial import unittest
import os, sets
from MailPing import config, fileutil
class TestConfig(unittest.TestCase):
def setUp(self):
self.configdir = self.mktemp()
os.mkdir(self.configdir)
def testTimeFail(self):
self.assertRaises(config.NoSuchConfigItem,
config.getTime,
self.configdir, 'not-exist')
def testTimeDefault(self):
class Unique:
pass
self.assertEquals(Unique,
config.getTime(self.configdir, 'not-exist',
Unique))
def testTimeOK(self):
fileutil.writeFile(os.path.join(self.configdir, 'sometimes'),
'42\n')
self.assertEquals(config.getTime(self.configdir, 'sometimes'),
42)
def testEmailFail(self):
self.assertRaises(config.NoSuchConfigItem,
config.getEmail,
self.configdir, 'not-exist')
def testEmailDefault(self):
class Unique:
pass
self.assertEquals(Unique,
config.getEmail(self.configdir, 'not-exist',
Unique))
def testEmailOK(self):
fileutil.writeFile(os.path.join(self.configdir, 'sometimes'),
'42\n')
self.assertEquals(config.getEmail(self.configdir, 'sometimes'),
'42')
mailping-0.0.4/MailPing/test/__init__.py 0000644 0001750 0001750 00000000000 10037211452 017110 0 ustar thijs thijs mailping-0.0.4/MailPing/test/test_maildir.py 0000644 0001750 0001750 00000006612 10040013501 020035 0 ustar thijs thijs from twisted.trial import unittest
import os, sets, email
from MailPing import maildir, fileutil
class TestMaildir(unittest.TestCase):
def setUp(self):
self.maildir = self.mktemp()
os.mkdir(self.maildir)
os.mkdir(os.path.join(self.maildir, 'cur'))
os.mkdir(os.path.join(self.maildir, 'new'))
os.mkdir(os.path.join(self.maildir, 'tmp'))
def testEmpty(self):
def _fail(*a, **kw):
raise FailTest
maildir.process(self.maildir, _fail)
def testCallback(self):
fileutil.writeFile(os.path.join(self.maildir, 'new',
'42.P34Q0.testhost'),
'''foo''')
fileutil.writeFile(os.path.join(self.maildir, 'new',
'42.P34Q1.testhost'),
'''bar''')
fileutil.writeFile(os.path.join(self.maildir, 'new',
'100.P43Q4.testhost'),
'''bar''')
seen = sets.Set()
def _store(path, filename):
seen.add(filename)
maildir.process(os.path.join(self.maildir),
_store)
self.assertEquals(seen,
sets.Set(['42.P34Q0.testhost',
'42.P34Q1.testhost',
'100.P43Q4.testhost']))
def testTimeFromFilename_Simple(self):
self.assertEquals(maildir.getTimeFromFilename('42.P34Q0.testhost'), 42)
def testTimeFromFilename_Microseconds_OK(self):
self.assertApproximates(maildir.getTimeFromFilename('42.M123P34Q0.testhost'), 42.000123, 0.000001)
self.assertApproximates(maildir.getTimeFromFilename('42.P34M123Q0.testhost'), 42.000123, 0.000001)
self.assertApproximates(maildir.getTimeFromFilename('42.P34Q0M123.testhost'), 42.000123, 0.000001)
def testTimeFromFilename_Microseconds_Nonnumeric(self):
self.assertEquals(maildir.getTimeFromFilename('42.Ma123P34Q0.testhost'), 42)
self.failUnless(isinstance(maildir.getTimeFromFilename('42.Ma123P34Q0.testhost'), int))
self.assertEquals(maildir.getTimeFromFilename('42.P34Ma123Q0.testhost'), 42)
self.failUnless(isinstance(maildir.getTimeFromFilename('42.P34Ma123Q0.testhost'), int))
self.assertEquals(maildir.getTimeFromFilename('42.P34Q0Ma123.testhost'), 42)
self.failUnless(isinstance(maildir.getTimeFromFilename('42.P34Q0Ma123.testhost'), int))
def testTimeFromFilename_Microseconds_Truncated(self):
self.assertEquals(maildir.getTimeFromFilename('42.MP34Q0.testhost'), 42)
self.failUnless(isinstance(maildir.getTimeFromFilename('42.MP34Q0.testhost'), int))
self.assertEquals(maildir.getTimeFromFilename('42.P34MQ0.testhost'), 42)
self.failUnless(isinstance(maildir.getTimeFromFilename('42.P34MQ0.testhost'), int))
self.assertEquals(maildir.getTimeFromFilename('42.P34Q0M.testhost'), 42)
self.failUnless(isinstance(maildir.getTimeFromFilename('42.P34Q0M.testhost'), int))
def testTimeFromFilename_Fail_NoPeriods(self):
self.assertEquals(maildir.getTimeFromFilename('foo'), None)
def testTimeFromFilename_Fail_OnePeriod(self):
self.assertEquals(maildir.getTimeFromFilename('foo.bar'), None)
def testTimeFromFilename_Fail_Nonnumeric(self):
self.assertEquals(maildir.getTimeFromFilename('foo.delivery.host'), None)
mailping-0.0.4/MailPing/__init__.py 0000644 0001750 0001750 00000001527 10037742112 016152 0 ustar thijs thijs """
Monitor email service availability and functioning.
"""
__copyright__ = "Copyright (C) 2004 Tommi Virtanen"
__license__ = """
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 2 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 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
"""
mailping-0.0.4/MailPing/incoming.py 0000644 0001750 0001750 00000004757 10040014610 016213 0 ustar thijs thijs import os
from MailPing import mail, maildir, fileutil
def process(statedir):
def _processEmail(subdir, filename):
ident = mail.getID(os.path.join(subdir, filename))
if ident is None:
maildir.create(os.path.join(subdir, '..', '..', 'junk'))
os.rename(os.path.join(subdir, filename),
os.path.join(subdir, '..', '..', 'junk', 'new', filename))
else:
pending = os.path.join(subdir,
'..', '..',
'pending', ident)
timestamp = fileutil.getTime(pending)
if timestamp < 0:
maildir.create(os.path.join(subdir, '..', '..', 'broken'))
os.rename(os.path.join(subdir, filename),
os.path.join(subdir, '..', '..', 'broken', 'new', filename))
else:
lastSuccess = fileutil.getTime(os.path.join(subdir,
'..', '..',
'success'))
if timestamp > lastSuccess:
os.rename(os.path.join(subdir, filename),
os.path.join(subdir, '..', '..', 'success.msg'))
os.rename(pending,
os.path.join(subdir, '..', '..', 'success'))
deliveryTime = maildir.getTimeFromFilename(filename)
if isinstance(deliveryTime, int):
# If delivery time has only 1 second precision,
# truncate current time to same accuracy, to avoid
# deliveries seeming to happen before creation
# of the pending file.
#
# The race could trigger if mailping-cron is
# run in a tight loop, or if it is later changed
# to do probe sending before incoming processing.
timestamp = int(timestamp)
if deliveryTime is not None and deliveryTime >= timestamp:
fileutil.writeFile(os.path.join(subdir, '..', '..', 'latency'),
'%f\n' % (deliveryTime - timestamp))
else:
os.unlink(os.path.join(subdir, filename))
os.unlink(pending)
maildir.process(os.path.join(statedir, 'incoming'),
_processEmail)
mailping-0.0.4/MailPing/probe.py 0000644 0001750 0001750 00000005434 10154027101 015515 0 ustar thijs thijs import os, errno
from MailPing import fileutil, mail
import smtplib
import email
from email.Utils import make_msgid
import random
def shouldSend(statedir, interval, curtime):
last = fileutil.getTime(os.path.join(statedir, 'success'))
try:
pending = os.listdir(os.path.join(statedir, 'pending'))
except OSError, e:
if e.errno == errno.ENOENT:
pass
else:
raise
else:
for filename in pending:
if filename.endswith('.tmp'):
continue
last = max(last,
fileutil.getTime(os.path.join(statedir,
'pending',
filename)))
return last + interval < curtime
MESSAGE_TEXT = """\
This is a mailping probe message sent to automatically test the
functioning of email between the addresses in the From and To
header fields.
This message should only be sent to explicitly configured addresses,
no human should ever receive this message.
This message is not spam. It is not sent by an email autoresponder.
If you are receiving this message, it means the person using
mailping misconfigured it. Please reply to this email to let them
know of this fact.
"""
def randomIdent():
return '%08x%08x%08x%08x%08x' % (
random.randint(0, 2**32-1),
random.randint(0, 2**32-1),
random.randint(0, 2**32-1),
random.randint(0, 2**32-1),
random.randint(0, 2**32-1),
)
def makeProbe(ident, fromAddress, toAddress, adminAddress=None):
msg = email.message_from_string(MESSAGE_TEXT)
mail.setMsgField(msg, 'From', fromAddress)
mail.setMsgField(msg, 'To', toAddress)
if adminAddress is not None:
mail.setMsgField(msg, 'Reply-To', adminAddress)
mail.setID(msg, ident)
msgid = make_msgid('mailping.%s' % ident)
mail.setMsgField(msg, 'Message-ID', msgid)
return msg
def send(msg, sender, recipient):
s = smtplib.SMTP()
s.connect()
s.sendmail(sender, [recipient], msg.as_string())
s.quit()
def process(statedir, interval, curtime,
fromAddress, toAddress, adminAddress):
if shouldSend(statedir, interval, curtime):
ident = randomIdent()
msg = makeProbe(ident=ident,
fromAddress=fromAddress,
toAddress=toAddress,
adminAddress=adminAddress)
send(msg,
sender=fromAddress,
recipient=toAddress)
pending = os.path.join(statedir, 'pending')
try:
os.mkdir(pending)
except OSError, e:
if e.errno == errno.EEXIST:
pass
else:
raise
fileutil.writeFile(os.path.join(pending, ident), '%f\n' % curtime)