removed another bunch of references to geni
[sfa.git] / sfa / plc / nodes.py
1 ### $Id$
2 ### $URL$
3
4 import os
5 import time
6 import datetime
7 import sys
8 import traceback
9
10 from sfa.util.namespace import *
11 from sfa.util.rspec import *
12 from sfa.util.specdict import * 
13 from sfa.util.faults import *
14 from sfa.util.storage import *
15 from sfa.util.debug import log
16 from sfa.util.rspec import *
17 from sfa.util.specdict import * 
18 from sfa.util.policy import Policy
19 from sfa.server.aggregate import Aggregates 
20
21 class Nodes(SimpleStorage):
22
23     def __init__(self, api, ttl = 1, origin_hrn=None):
24         self.api = api
25         self.ttl = ttl
26         self.threshold = None
27         path = self.api.config.SFA_DATA_DIR
28         filename = ".".join([self.api.interface, self.api.hrn, "nodes"])
29         filepath = path + os.sep + filename
30         self.nodes_file = filepath
31         SimpleStorage.__init__(self, self.nodes_file)
32         self.policy = Policy(api)
33         self.load()
34         self.origin_hrn = origin_hrn
35
36
37     def refresh(self):
38         """
39         Update the cached list of nodes
40         """
41
42         # Reload components list
43         now = datetime.datetime.now()
44         if not self.has_key('threshold') or not self.has_key('timestamp') or \
45            now > datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format))): 
46             if self.api.interface in ['aggregate']:
47                 self.refresh_nodes_aggregate()
48             elif self.api.interface in ['slicemgr']:
49                 self.refresh_nodes_smgr()
50
51     def refresh_nodes_aggregate(self):
52         rspec = RSpec()
53         rspec.parseString(self.get_rspec())
54         
55         # filter nodes according to policy
56         blist = self.policy['node_blacklist']
57         wlist = self.policy['node_whitelist']
58         rspec.filter('NodeSpec', 'name', blacklist=blist, whitelist=wlist)
59
60         # extract ifspecs from rspec to get ips'
61         ips = []
62         ifspecs = rspec.getDictsByTagName('IfSpec')
63         for ifspec in ifspecs:
64             if ifspec.has_key('addr') and ifspec['addr']:
65                 ips.append(ifspec['addr'])
66
67         # extract nodespecs from rspec to get dns names
68         hostnames = []
69         nodespecs = rspec.getDictsByTagName('NodeSpec')
70         for nodespec in nodespecs:
71             if nodespec.has_key('name') and nodespec['name']:
72                 hostnames.append(nodespec['name'])
73
74         # update timestamp and threshold
75         timestamp = datetime.datetime.now()
76         hr_timestamp = timestamp.strftime(self.api.time_format)
77         delta = datetime.timedelta(hours=self.ttl)
78         threshold = timestamp + delta
79         hr_threshold = threshold.strftime(self.api.time_format)
80
81         node_details = {}
82         node_details['rspec'] = rspec.toxml()
83         node_details['ip'] = ips
84         node_details['dns'] = hostnames
85         node_details['timestamp'] = hr_timestamp
86         node_details['threshold'] = hr_threshold
87         # save state 
88         self.update(node_details)
89         self.write()       
90  
91     def get_remote_resources(self, hrn = None):
92         # convert and threshold to ints
93         if self.has_key('timestamp') and self['timestamp']:
94             hr_timestamp = self['timestamp']
95             timestamp = datetime.datetime.fromtimestamp(time.mktime(time.strptime(hr_timestamp, self.api.time_format)))
96             hr_threshold = self['threshold']
97             threshold = datetime.datetime.fromtimestamp(time.mktime(time.strptime(hr_threshold, self.api.time_format)))
98         else:
99             timestamp = datetime.datetime.now()
100             hr_timestamp = timestamp.strftime(self.api.time_format)
101             delta = datetime.timedelta(hours=self.ttl)
102             threshold = timestamp + delta
103             hr_threshold = threshold.strftime(self.api.time_format)
104
105         start_time = int(timestamp.strftime("%s"))
106         end_time = int(threshold.strftime("%s"))
107         duration = end_time - start_time
108
109         aggregates = Aggregates(self.api)
110         rspecs = {}
111         networks = []
112         rspec = RSpec()
113         credential = self.api.getCredential()
114         origin_hrn = self.origin_hrn
115         for aggregate in aggregates:
116           if aggregate not in [self.api.auth.client_cred.get_gid_caller().get_hrn()]:
117             try:
118                 # get the rspec from the aggregate
119                 agg_rspec = aggregates[aggregate].get_resources(credential, hrn, origin_hrn)
120                 # extract the netspec from each aggregates rspec
121                 rspec.parseString(agg_rspec)
122                 networks.extend([{'NetSpec': rspec.getDictsByTagName('NetSpec')}])
123             except:
124                 # XX print out to some error log
125                 print >> log, "Error getting resources at aggregate %s" % aggregate
126                 traceback.print_exc(log)
127                 print >> log, "%s" % (traceback.format_exc())
128         # create the rspec dict
129         resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
130         resourceDict = {'RSpec': resources}
131         # convert rspec dict to xml
132         rspec.parseDict(resourceDict)
133         return rspec
134
135     def refresh_nodes_smgr(self):
136
137         rspec = self.get_remote_resources()        
138         # filter according to policy
139         blist = self.policy['node_blacklist']
140         wlist = self.policy['node_whitelist']    
141         rspec.filter('NodeSpec', 'name', blacklist=blist, whitelist=wlist)
142
143         # update timestamp and threshold
144         timestamp = datetime.datetime.now()
145         hr_timestamp = timestamp.strftime(self.api.time_format)
146         delta = datetime.timedelta(hours=self.ttl)
147         threshold = timestamp + delta
148         hr_threshold = threshold.strftime(self.api.time_format)
149
150         nodedict = {'rspec': rspec.toxml(),
151                     'timestamp': hr_timestamp,
152                     'threshold':  hr_threshold}
153
154         self.update(nodedict)
155         self.write()
156
157     def get_rspec(self, hrn = None):
158
159         if self.api.interface in ['slicemgr']:
160             return self.get_rspec_smgr(hrn)
161         elif self.api.interface in ['aggregate']:
162             return self.get_rspec_aggregate(hrn)     
163
164     def get_rspec_smgr(self, hrn = None):
165         
166         rspec = self.get_remote_resources(hrn)
167         return rspec.toxml()
168
169     def get_rspec_aggregate(self, hrn = None):
170         """
171         Get resource information from PLC
172         """
173
174         slicename = None
175         # Get the required nodes
176         if not hrn:
177             nodes = self.api.plshell.GetNodes(self.api.plauth, {'peer_id': None})
178             try:  linkspecs = self.api.plshell.GetLinkSpecs() # if call is supported
179             except:  linkspecs = []
180         else:
181             slicename = hrn_to_pl_slicename(hrn)
182             slices = self.api.plshell.GetSlices(self.api.plauth, [slicename])
183             if not slices:
184                 nodes = []
185             else:
186                 slice = slices[0]
187                 node_ids = slice['node_ids']
188                 nodes = self.api.plshell.GetNodes(self.api.plauth, {'peer_id': None, 'node_id': node_ids})
189
190         # Filter out whitelisted nodes
191         public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
192             
193         # ...only if they are not already assigned to this slice.
194         if (not slicename):        
195             nodes = filter(public_nodes, nodes)
196
197         # Get all network interfaces
198         interface_ids = []
199         for node in nodes:
200             # The field name has changed in plcapi 4.3
201             if self.api.plshell_version in ['4.2']:
202                 interface_ids.extend(node['nodenetwork_ids'])
203             elif self.api.plshell_version in ['4.3']:
204                 interface_ids.extend(node['interface_ids'])
205             else:
206                 raise SfaAPIError, "Unsupported plcapi version ", \
207                                  self.api.plshell_version
208
209         if self.api.plshell_version in ['4.2']:
210             interfaces = self.api.plshell.GetNodeNetworks(self.api.plauth, interface_ids)
211         elif self.api.plshell_version in ['4.3']:
212             interfaces = self.api.plshell.GetInterfaces(self.api.plauth, interface_ids)
213         else:
214             raise SfaAPIError, "Unsupported plcapi version ", \
215                                 self.api.plshell_version 
216         interface_dict = {}
217         for interface in interfaces:
218             if self.api.plshell_version in ['4.2']:
219                 interface_dict[interface['nodenetwork_id']] = interface
220             elif self.api.plshell_version in ['4.3']:
221                 interface_dict[interface['interface_id']] = interface
222             else:
223                 raise SfaAPIError, "Unsupported plcapi version", \
224                                     self.api.plshell_version 
225
226         # join nodes with thier interfaces
227         for node in nodes:
228             node['interfaces'] = []
229             if self.api.plshell_version in ['4.2']:
230                 for nodenetwork_id in node['nodenetwork_ids']:
231                     node['interfaces'].append(interface_dict[nodenetwork_id])
232             elif self.api.plshell_version in ['4.3']:
233                 for interface_id in node['interface_ids']:
234                     node['interfaces'].append(interface_dict[interface_id])
235             else:
236                 raise SfaAPIError, "Unsupported plcapi version", \
237                                     self.api.plshell_version
238
239         # convert and threshold to ints
240         if self.has_key('timestamp') and self['timestamp']:
241             timestamp = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['timestamp'], self.api.time_format)))
242             threshold = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format)))
243         else:
244             timestamp = datetime.datetime.now()
245             delta = datetime.timedelta(hours=self.ttl)
246             threshold = timestamp + delta
247
248         start_time = int(timestamp.strftime("%s"))
249         end_time = int(threshold.strftime("%s"))
250         duration = end_time - start_time
251
252         # create the plc dict
253         networks = [{'nodes': nodes,
254                      'name': self.api.hrn,
255                      'start_time': start_time,
256                      'duration': duration}]
257         if not hrn:
258             networks[0]['links'] = linkspecs
259         resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
260
261         # convert the plc dict to an rspec dict
262         resourceDict = RSpecDict(resources)
263         # convert the rspec dict to xml
264         rspec = RSpec()
265         rspec.parseDict(resourceDict)
266         return rspec.toxml()
267