First draft for leases
[plcapi.git] / PLC / Methods / UpdateLeases.py
1 # $Id$
2 # $URL$
3 from PLC.Faults import *
4 from PLC.Method import Method
5 from PLC.Parameter import Parameter, Mixed
6 from PLC.Auth import Auth
7
8 from PLC.Timestamp import Timestamp, Duration
9
10 from PLC.Leases import Lease, Leases
11 from PLC.Slices import Slice, Slices
12
13 can_update = lambda (field, value): field in ['t_from', 't_until', 'duration']
14
15 class UpdateLeases(Method):
16     """
17     Updates the parameters of a (set of) existing lease(s) with the values in
18     lease_fields; specifically this applies to the timeslot definition.
19     As a convenience you may, in addition to the t_from and t_until fields,
20     you can also set the 'duration' field.
21
22     Users may only update leases attached to their slices. 
23     PIs may update any of the leases for slices at their sites, or any
24     slices of which they are members. Admins may update any lease.
25
26     Returns a dict of successfully updated lease_ids and error messages.
27     """
28
29     roles = ['admin', 'pi', 'tech', 'user']
30
31     lease_fields = dict(filter(can_update, Lease.fields.items()))
32
33     accepts = [
34         Auth(),
35         Mixed (Lease.fields['lease_id'],
36                [Lease.fields['lease_id']]),
37         lease_fields
38         ]
39
40     returns = Parameter(dict, " 'updated_ids' is the list ids updated, 'errors' is a list of error strings")
41
42     debug=False
43 #    debug=True
44
45     def call(self, auth, lease_ids, input_fields):
46         input_fields = dict(filter(can_update, input_fields.items()))
47
48         if 'duration' in input_fields:
49             if 't_from' in input_fields and 't_until' in input_fields:
50                 raise PLCInvalidArgument, "Cannot set t_from AND t_until AND duration"
51             # specify 'duration':0 to keep duration unchanged
52             if input_fields['duration'] : input_fields['duration']=Duration.validate(input_fields['duration'])
53
54         # Get lease information
55         leases = Leases(self.api, lease_ids)
56         if not leases:
57             raise PLCInvalidArgument, "No such leases %r"%lease_ids
58
59         # fetch related slices
60         slices = Slices(self.api, [ lease['slice_id'] for lease in leases],['slice_id','person_ids'])
61         # create hash on slice_id
62         slice_map = dict ( [ (slice['slice_id'],slice) for slice in slices ] )
63
64         updated_ids=[]
65         errors=[]
66
67         lease_ids=[lease['lease_id'] for lease in leases]
68         for lease in leases:
69
70             if 'admin' not in self.caller['roles']:
71                 slice=slice_map[lease['slice_id']]
72                 # check slices only once
73                 if not slice.has_key('verified'):
74                     if self.caller['person_id'] in slice['person_ids']:
75                         pass
76                     elif 'pi' not in self.caller['roles']:
77                         raise PLCPermissionDenied, "Not a member of slice %r"%slice['name']
78                     elif slice['site_id'] not in self.caller['site_ids']:
79                         raise PLCPermissionDenied, "Slice %r not associated with any of your sites"%slice['name']
80             slice['verified']=True
81
82             try:
83                 # we've ruled out already the case where all 3 (from, to, duration) where specified
84                 if 'duration' not in input_fields:
85                     lease_fields=input_fields
86                 else:
87                     # all arithmetics on longs..
88                     duration=Duration.validate(input_fields['duration'])
89                     # specify 'duration':0 to keep duration unchanged
90                     if not duration: 
91                         duration = Timestamp.cast_long(lease['t_until'])-Timestamp.cast_long(lease['t_from'])
92                     if 't_from' in input_fields:
93                         lease_fields={'t_from':input_fields['t_from'],
94                                       't_until':Timestamp.cast_long(input_fields['from'])+duration}
95                     elif 't_until' in input_fields:
96                         lease_fields={'t_from':Timestamp.cast_long(input_fields['t_until'])-duration,
97                                       't_until':input_fields['t_until']}
98                     else:
99                         lease_fields={'t_until':Timestamp.cast_long(lease['t_from'])+duration}
100                 if UpdateLeases.debug: 
101                     print 'lease_fields',lease_fields
102                     for k in [ 't_from', 't_until'] :
103                         if k in lease_fields: print k,'aka',Timestamp.sql_validate_utc(lease_fields[k])
104                 
105                 lease.update(lease_fields)
106                 lease.sync()
107                 updated_ids.append(lease['lease_id'])
108             except Exception,e:
109                 errors.append("Could not update lease %d - check new time limits ? -- %r"%(lease['lease_id'],e))
110         
111         # Logging variables
112         self.event_objects = {'Lease': updated_ids}
113         self.message = 'lease %r updated: %s' %  (lease_ids, ", ".join(input_fields.keys()))
114
115         return {'updated_ids' : updated_ids,
116                 'errors' : errors }