expose leases to nodes
[plcapi.git] / PLC / Methods / GetSlivers.py
1 # $Id$
2 # $URL$
3 import time
4
5 from PLC.Faults import *
6 from PLC.Method import Method
7 from PLC.Parameter import Parameter, Mixed
8 from PLC.Filter import Filter
9 from PLC.Auth import Auth
10 from PLC.Nodes import Node, Nodes
11 from PLC.Interfaces import Interface, Interfaces
12 from PLC.NodeGroups import NodeGroup, NodeGroups
13 from PLC.ConfFiles import ConfFile, ConfFiles
14 from PLC.Slices import Slice, Slices
15 from PLC.Persons import Person, Persons
16 from PLC.Sites import Sites
17 from PLC.Roles import Roles
18 from PLC.Keys import Key, Keys
19 from PLC.SliceTags import SliceTag, SliceTags
20 from PLC.InitScripts import InitScript, InitScripts
21 from PLC.Leases import Lease, Leases
22 from PLC.Timestamp import Duration
23 from PLC.Methods.GetSliceFamily import GetSliceFamily
24
25 from PLC.Accessors.Accessors_standard import *
26
27 # XXX used to check if slice expiration time is sane
28 MAXINT =  2L**31-1
29
30 def get_slivers(api, auth, slice_filter, node = None):
31     # Get slice information
32     slices = Slices(api, slice_filter, ['slice_id', 'name', 'instantiation', 'expires', 'person_ids', 'slice_tag_ids'])
33
34     # Build up list of users and slice attributes
35     person_ids = set()
36     slice_tag_ids = set()
37     for slice in slices:
38         person_ids.update(slice['person_ids'])
39         slice_tag_ids.update(slice['slice_tag_ids'])
40
41     # Get user information
42     all_persons = Persons(api, {'person_id':person_ids,'enabled':True}, ['person_id', 'enabled', 'key_ids']).dict()
43
44     # Build up list of keys
45     key_ids = set()
46     for person in all_persons.values():
47         key_ids.update(person['key_ids'])
48
49     # Get user account keys
50     all_keys = Keys(api, key_ids, ['key_id', 'key', 'key_type']).dict()
51
52     # Get slice attributes
53     all_slice_tags = SliceTags(api, slice_tag_ids).dict()
54
55     slivers = []
56     for slice in slices:
57         keys = []
58         for person_id in slice['person_ids']:
59             if person_id in all_persons:
60                 person = all_persons[person_id]
61                 if not person['enabled']:
62                     continue
63                 for key_id in person['key_ids']:
64                     if key_id in all_keys:
65                         key = all_keys[key_id]
66                         keys += [{'key_type': key['key_type'],
67                                   'key': key['key']}]
68
69         attributes = []
70
71         # All (per-node and global) attributes for this slice
72         slice_tags = []
73         for slice_tag_id in slice['slice_tag_ids']:
74             if slice_tag_id in all_slice_tags:
75                 slice_tags.append(all_slice_tags[slice_tag_id])
76
77         # Per-node sliver attributes take precedence over global
78         # slice attributes, so set them first.
79         # Then comes nodegroup slice attributes
80         # Followed by global slice attributes
81         sliver_attributes = []
82
83         if node is not None:
84             for sliver_attribute in [ a for a in slice_tags if a['node_id'] == node['node_id'] ]:
85                 sliver_attributes.append(sliver_attribute['tagname'])
86                 attributes.append({'tagname': sliver_attribute['tagname'],
87                                    'value': sliver_attribute['value']})
88
89             # set nodegroup slice attributes
90             for slice_tag in [ a for a in slice_tags if a['nodegroup_id'] in node['nodegroup_ids'] ]:
91                 # Do not set any nodegroup slice attributes for
92                 # which there is at least one sliver attribute
93                 # already set.
94                 if slice_tag not in slice_tags:
95                     attributes.append({'tagname': slice_tag['tagname'],
96                                    'value': slice_tag['value']})
97
98         for slice_tag in [ a for a in slice_tags if a['node_id'] is None ]:
99             # Do not set any global slice attributes for
100             # which there is at least one sliver attribute
101             # already set.
102             if slice_tag['tagname'] not in sliver_attributes:
103                 attributes.append({'tagname': slice_tag['tagname'],
104                                    'value': slice_tag['value']})
105
106         # XXX Sanity check; though technically this should be a system invariant
107         # checked with an assertion
108         if slice['expires'] > MAXINT:  slice['expires']= MAXINT
109
110         # expose the slice vref as computed by GetSliceFamily
111         family = GetSliceFamily (api).call(auth, slice['slice_id'])
112
113         slivers.append({
114             'name': slice['name'],
115             'slice_id': slice['slice_id'],
116             'instantiation': slice['instantiation'],
117             'expires': slice['expires'],
118             'keys': keys,
119             'attributes': attributes,
120             'GetSliceFamily': family,
121             })
122
123     return slivers
124
125 class GetSlivers(Method):
126     """
127     Returns a struct containing information about the specified node
128     (or calling node, if called by a node and node_id_or_hostname is
129     not specified), including the current set of slivers bound to the
130     node.
131
132     All of the information returned by this call can be gathered from
133     other calls, e.g. GetNodes, GetInterfaces, GetSlices, etc. This
134     function exists almost solely for the benefit of Node Manager.
135     """
136
137     roles = ['admin', 'node']
138
139     accepts = [
140         Auth(),
141         Mixed(Node.fields['node_id'],
142               Node.fields['hostname']),
143         ]
144
145     returns = {
146         'timestamp': Parameter(int, "Timestamp of this call, in seconds since UNIX epoch"),
147         'node_id': Node.fields['node_id'],
148         'hostname': Node.fields['hostname'],
149         'interfaces': [Interface.fields],
150         'groups': [NodeGroup.fields['groupname']],
151         'conf_files': [ConfFile.fields],
152         'initscripts': [InitScript.fields],
153         'accounts': [{
154             'name': Parameter(str, "unix style account name", max = 254),
155             'keys': [{
156                 'key_type': Key.fields['key_type'],
157                 'key': Key.fields['key']
158             }],
159             }],
160         'slivers': [{
161             'name': Slice.fields['name'],
162             'slice_id': Slice.fields['slice_id'],
163             'instantiation': Slice.fields['instantiation'],
164             'expires': Slice.fields['expires'],
165             'keys': [{
166                 'key_type': Key.fields['key_type'],
167                 'key': Key.fields['key']
168             }],
169             'attributes': [{
170                 'tagname': SliceTag.fields['tagname'],
171                 'value': SliceTag.fields['value']
172             }]
173         }],
174         'xmpp': {'server':Parameter(str,"hostname for the XMPP server"),
175                  'user':Parameter(str,"username for the XMPP server"),
176                  'password':Parameter(str,"username for the XMPP server"),
177                  },
178         'leases': [  { 'slice_id' : Lease.fields['slice_id'],
179                        't_from' : Lease.fields['t_from'],
180                        't_until' : Lease.fields['t_until'],
181                        }],
182     }
183
184     def call(self, auth, node_id_or_hostname = None):
185         timestamp = int(time.time())
186
187         # Get node
188         if node_id_or_hostname is None:
189             if isinstance(self.caller, Node):
190                 node = self.caller
191             else:
192                 raise PLCInvalidArgument, "'node_id_or_hostname' not specified"
193         else:
194             nodes = Nodes(self.api, [node_id_or_hostname])
195             if not nodes:
196                 raise PLCInvalidArgument, "No such node"
197             node = nodes[0]
198
199             if node['peer_id'] is not None:
200                 raise PLCInvalidArgument, "Not a local node"
201
202         # Get interface information
203         interfaces = Interfaces(self.api, node['interface_ids'])
204
205         # Get node group information
206         nodegroups = NodeGroups(self.api, node['nodegroup_ids']).dict('groupname')
207         groups = nodegroups.keys()
208
209         # Get all (enabled) configuration files
210         all_conf_files = ConfFiles(self.api, {'enabled': True}).dict()
211         conf_files = {}
212
213         # Global configuration files are the default. If multiple
214         # entries for the same global configuration file exist, it is
215         # undefined which one takes precedence.
216         for conf_file in all_conf_files.values():
217             if not conf_file['node_ids'] and not conf_file['nodegroup_ids']:
218                 conf_files[conf_file['dest']] = conf_file
219         
220         # Node group configuration files take precedence over global
221         # ones. If a node belongs to multiple node groups for which
222         # the same configuration file is defined, it is undefined
223         # which one takes precedence.
224         for nodegroup in nodegroups.values():
225             for conf_file_id in nodegroup['conf_file_ids']:
226                 if conf_file_id in all_conf_files:
227                     conf_file = all_conf_files[conf_file_id]
228                     conf_files[conf_file['dest']] = conf_file
229         
230         # Node configuration files take precedence over node group
231         # configuration files.
232         for conf_file_id in node['conf_file_ids']:
233             if conf_file_id in all_conf_files:
234                 conf_file = all_conf_files[conf_file_id]
235                 conf_files[conf_file['dest']] = conf_file            
236
237         # Get all (enabled) initscripts
238         initscripts = InitScripts(self.api, {'enabled': True})  
239
240         # Get system slices
241         system_slice_tags = SliceTags(self.api, {'tagname': 'system', 'value': '1'}).dict('slice_id')
242         system_slice_ids = system_slice_tags.keys()
243         
244         # Get nm-controller slices
245         # xxx Thierry: should these really be exposed regardless of their mapping to nodes ?
246         controller_and_delegated_slices = Slices(self.api, {'instantiation': ['nm-controller', 'delegated']}, ['slice_id']).dict('slice_id')
247         controller_and_delegated_slice_ids = controller_and_delegated_slices.keys()
248         slice_ids = system_slice_ids + controller_and_delegated_slice_ids + node['slice_ids']
249
250         slivers = get_slivers(self.api, auth, slice_ids, node)
251
252         # get the special accounts and keys needed for the node
253         # root
254         # site_admin
255         accounts = []
256         if False and 'site_id' not in node:
257             nodes = Nodes(self.api, node['node_id'])
258             node = nodes[0]
259
260         # used in conjunction with reduce to flatten lists, like in
261         # reduce ( reduce_flatten_list, [ [1] , [2,3] ], []) => [ 1,2,3 ]
262         def reduce_flatten_list (x,y): return x+y
263
264         # power users are pis and techs
265         def get_site_power_user_keys(api,site_id_or_name):
266             site = Sites (api,site_id_or_name,['person_ids'])[0]
267             key_ids = reduce (reduce_flatten_list, 
268                               [ p['key_ids'] for p in \
269                                     Persons(api,{ 'person_id':site['person_ids'], 
270                                                   'enabled':True, '|role_ids' : [20, 40] }, 
271                                             ['key_ids']) ],
272                               [])
273             return [ key['key'] for key in Keys (api, key_ids) if key['key_type']=='ssh']
274
275         # all admins regardless of their site
276         def get_all_admin_keys(api):
277             key_ids = reduce (reduce_flatten_list, 
278                               [ p['key_ids'] for p in \
279                                     Persons(api, {'peer_id':None, 'enabled':True, '|role_ids':[10] }, 
280                                             ['key_ids']) ],
281                               [])
282             return [ key['key'] for key in Keys (api, key_ids) if key['key_type']=='ssh']
283
284         # 'site_admin' account setup
285         personsitekeys=get_site_power_user_keys(self.api,node['site_id'])
286         accounts.append({'name':'site_admin','keys':personsitekeys})
287
288         # 'root' account setup on nodes from all 'admin' users
289         personsitekeys=get_all_admin_keys(self.api)
290         accounts.append({'name':'root','keys':personsitekeys})
291
292         hrn = GetNodeHrn(self.api).call(auth,node['node_id'])
293
294         # XMPP config for omf federation
295         try:
296             if not self.api.config.PLC_OMF_ENABLED:
297                 raise Exception,"OMF disabled"
298             xmpp={'server':self.api.config.PLC_OMF_XMPP_SERVER,
299                   'user':self.api.config.PLC_OMF_XMPP_USER,
300                   'password':self.api.config.PLC_OMF_XMPP_PASSWORD,
301                   }
302         except:
303             xmpp={'server':None,'user':None,'password':None}
304
305         node.update_last_contact()
306
307         # expose leases
308         lease_exposed_fields = [ 'slice_id', 't_from', 't_until', ]
309         leases=None
310         if node['node_type'] == 'reservable':
311             # expose the leases for the next 12 hours
312             leases = [ dict ( [ (k,l[k]) for k in lease_exposed_fields ] ) 
313                        for l in Leases (self.api, {'node_id':node['node_id'],
314                                                    'clip': (timestamp, timestamp+12*Duration.HOUR)}) ]
315
316         return {
317             'timestamp': timestamp,
318             'node_id': node['node_id'],
319             'hostname': node['hostname'],
320             'interfaces': interfaces,
321             'groups': groups,
322             'conf_files': conf_files.values(),
323             'initscripts': initscripts,
324             'slivers': slivers,
325             'accounts': accounts,
326             'xmpp':xmpp,
327             'hrn':hrn,
328             'leases':leases,
329             }