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