2 ## vim:set et ts=2 sw=2 ai:
3 # Send email reminders to users having sizable homedirs.
5 # Copyright (c) 2013 Philipp Kern <phil@philkern.de>
6 # Copyright (c) 2013 Peter Palfrader <peter@palfrader.org>
7 # Copyright (c) 2013 Luca Filipozzi <lfilipoz@debian.org>
9 # Permission is hereby granted, free of charge, to any person obtaining a copy
10 # of this software and associated documentation files (the "Software"), to deal
11 # in the Software without restriction, including without limitation the rights
12 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 # copies of the Software, and to permit persons to whom the Software is
14 # furnished to do so, subject to the following conditions:
16 # The above copyright notice and this permission notice shall be included in
17 # all copies or substantial portions of the Software.
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 from __future__ import print_function
29 from collections import defaultdict
31 import email.mime.text
43 # avoid base64 encoding for utf-8
44 email.charset.add_charset('utf-8', email.charset.SHORTEST, email.charset.QP)
46 SENDMAIL = ['/usr/sbin/sendmail', '-t', '-oi']
47 #SENDMAIL = ['/bin/cat']
51 {hostname}'s /home is, unfortunately, not infinite in size. If you have
52 anything in there that you no longer need, please clean it up."""
54 Can you please look at your $HOME on {hostname} and remove files which
55 you no longer need (such as old sources)."""
57 Thanks for your porting effort on {hostname}!
59 Please note that on most porterboxes /home is quite small, so please remove
60 files that you do not need anymore."""
64 { 'days': 5, 'size': 10240 },
65 { 'days': 10, 'size': 1024 },
66 { 'days': 30, 'size': 100 },
67 { 'days': 60, 'size': 60 },
68 { 'days': 90, 'size': 10 }
70 EXCLUDED_USERNAMES = ['lost+found']
71 MAIL_FROM = 'debian-admin (via Cron) <bulk@admin.debian.org>'
72 MAIL_TO = '{username}@{hostname}.debian.org'
73 MAIL_CC = 'debian-admin (bulk sink) <bulk@admin.debian.org>'
74 MAIL_REPLYTO = 'debian-admin <dsa@debian.org>'
75 MAIL_SUBJECT = 'Please clean up ~{username} on {hostname}.debian.org'
81 For your information, you last logged into {hostname} {days_ago} days
82 ago, and your home directory there is {homedir_size} MB in size.
84 If you currently do not use {hostname}, please keep ~{username} under
87 Please assist us in freeing up space by deleting schroots, also.
91 Debian System Administration Team via Cron
93 PS: replies not required.
96 class Error(Exception):
99 class SendmailError(Error):
102 class LastlogTimes(dict):
103 LASTLOG_STRUCT = '=L32s256s'
106 record_size = struct.calcsize(self.LASTLOG_STRUCT)
107 with open('/var/log/lastlog', 'r') as fp:
108 uid = -1 # there is one record per uid in lastlog
109 for record in iter(lambda: fp.read(record_size), ''):
110 uid += 1 # so keep incrementing uid for each record read
111 lastlog_time, _, _ = list(struct.unpack(self.LASTLOG_STRUCT, record))
112 if lastlog_time == 0:
115 self[pwd.getpwuid(uid).pw_name] = lastlog_time
117 logging.error('could not resolve username from uid')
120 class HomedirSizes(dict):
122 for direntry in glob.glob('/home/*'):
123 username = os.path.basename(direntry)
124 if username in EXCLUDED_USERNAMES:
127 pwinfo = pwd.getpwnam(username)
129 if os.path.isdir(direntry):
130 logging.warning('directory %s exists on %s but there is no %s user', direntry, platform.node(), username)
132 command = ['/usr/bin/du', '-ms', pwinfo.pw_dir]
133 p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
134 (stdout, stderr) = p.communicate()
135 if p.returncode != 0: # ignore errors from du
136 logging.info('%s failed:', ' '.join(command))
140 self[username] = int(stdout.split('\t')[0])
142 logging.error('could not convert size output from %s: %s', ' '.join(command), stdout)
145 class HomedirReminder(object):
147 self.lastlog_times = LastlogTimes()
148 self.homedir_sizes = HomedirSizes()
150 def send_mail(self, **kwargs):
151 msg = email.mime.text.MIMEText(MAIL_MESSAGE.format(**kwargs), _charset='UTF-8')
152 msg['From'] = MAIL_FROM.format(**kwargs)
153 msg['To'] = MAIL_TO.format(**kwargs)
155 msg['Cc'] = MAIL_CC.format(**kwargs)
156 if MAIL_REPLYTO != "":
157 msg['Reply-To'] = MAIL_REPLYTO.format(**kwargs)
158 msg['Subject'] = MAIL_SUBJECT.format(**kwargs)
159 msg['Precedence'] = "bulk"
160 msg['Auto-Submitted'] = "auto-generated by mail-big-homedirs"
161 p = subprocess.Popen(SENDMAIL, stdin=subprocess.PIPE)
162 p.communicate(msg.as_string())
163 logging.debug(msg.as_string())
164 if p.returncode != 0:
168 current_time = time.time()
169 for username, homedir_size in self.homedir_sizes.iteritems():
171 name = pwd.getpwnam(username).pw_gecos.decode('utf-8').split(',', 1)[0].split(' ', 1)[0]
174 lastlog_time = self.lastlog_times[username]
175 days_ago = int( (current_time - lastlog_time) / 3600 / 24 )
176 if [x for x in CRITERIA if days_ago >= x['days'] and homedir_size >= x['size']]:
177 explanation = EXPLANATIONS[random.randint(0,len(EXPLANATIONS)-1)].format(hostname=platform.node())
178 self.send_mail(hostname=platform.node(), username=username, name=name, explanation=explanation, homedir_size=homedir_size, days_ago=days_ago)
180 if __name__ == '__main__':
181 logging.basicConfig()
182 # DEBUG for debugging, ERROR for production.
183 logging.getLogger().setLevel(logging.ERROR)
184 HomedirReminder().run()