220fd14e5dac1388be795226fee6a0feba42b6db
[myplc.git] / support-scripts / renew_reminder.py
1 #!/usr/bin/python
2 #
3 # Notify users of slices that are about to expire
4 #
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2005 The Trustees of Princeton University
7 #
8 # $Id$
9 #
10
11 import os
12 import sys
13 import time
14 from optparse import OptionParser
15
16 # Load shell with default configuration
17 sys.path.append('/usr/share/plc_api')
18 from PLC.Shell import Shell
19 plc = Shell(globals())
20
21 PLC_WWW_HOST = plc.config.PLC_WWW_HOST
22 PLC_NAME = plc.config.PLC_NAME
23
24 LOGFILE = '/var/log/renew_reminder'
25 class Logfile:
26     def __init__(self, filename):
27         self.filename = filename
28     def write(self, data):
29         try:
30             fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0644)
31             os.write(fd, '%s' % data)
32             os.close(fd)
33         except OSError:
34             sys.stderr.write(data)
35             sys.stderr.flush()
36
37 log = Logfile(LOGFILE)
38
39 # Debug
40 verbose = False;
41
42 # E-mail parameteres
43 slice_url = """https://%(PLC_WWW_HOST)s/db/slices/index.php?id=""" % locals()
44
45 parser = OptionParser()
46 parser.add_option("-s", "--slice", action = "append", dest = "slices", default = None,
47                   help = "Slice(s) to check (default: all)")
48 parser.add_option("-x", "--expires", type = "int", default = 5,
49                   help = "Warn if slice expires this many days from now (default: %default)")
50 parser.add_option("-n", "--dryrun", action = "store_true", default = False,
51                   help = "Dry run, do not actually e-mail users (default: %default)")
52 parser.add_option("-f", "--force", action = "store_true", default = False,
53                   help = "Force, send e-mail even if slice is not close to expiring (default: %default)")
54 parser.add_option("-v", "--verbose", action = "store_true", default = False,
55                   help = "Be verbose (default: %default)")
56 (options, args) = parser.parse_args()
57
58 now = int(time.time())
59 expires = now + (options.expires * 24 * 60 * 60)
60
61 if options.verbose:
62     print "Checking for slices that expire before " + time.ctime(expires)
63
64 slice_filter = {'peer_id': None}
65 if options.slices:
66     slice_filter['name'] = options.slices
67
68 for slice in GetSlices(slice_filter, ['slice_id', 'name', 'expires', 'description', 'url', 'person_ids']):
69     # See if slice expires before the specified warning date
70     if not options.force and slice['expires'] > expires:
71         continue
72
73     # Calculate number of whole days left
74     delta = slice['expires'] - now
75     days = delta / 24 / 60 / 60
76     if days == 0:
77         days = "less than a day"
78     else:
79         if days > 1:
80             suffix = "s"
81         else:
82             suffix = ""
83         days = "%d day%s" % (days, suffix)
84
85     name = slice['name']
86     slice_id = slice['slice_id']
87
88     message = """
89 The %(PLC_NAME)s slice %(name)s will expire in %(days)s.
90 """
91
92     # Explain that slices must have descriptions and URLs
93     if not slice['description'] or not slice['description'].strip() or \
94        not slice['url'] or not slice['url'].strip():
95         message += """
96 Before you may renew this slice, you must provide a short description
97 of the slice and a link to a project website.
98 """
99
100     # Provide links to renew or delete the slice
101     message += """
102 To update, renew, or delete this slice, visit the URL:
103
104         %(slice_url)s%(slice_id)d
105 """
106
107     emails = [person['email'] for person in GetPersons(slice['person_ids'], ['email'])]
108     if not emails: emails = ['no contacts']     
109     log_details = [time.ctime(now), slice['name'], time.ctime(slice['expires'])]
110     log_data = "%s\t%s" % ("\t".join(log_details), ",".join(emails))
111
112     # Send it
113     if slice['person_ids']:
114         if options.dryrun:
115             print message % locals()
116             print "log >> %s" % log_data
117         else:
118             NotifyPersons(slice['person_ids'],
119                           "%(PLC_NAME)s slice %(name)s expires in %(days)s" % locals(),
120                           message % locals())
121             print >> log, log_data
122             
123     elif options.verbose:
124         print slice['name'], "has no users, skipping"
125         print >> log, log_data